Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyError when finding for max value in nested dictionary

I have a nested dictionary like this:

input_dic = {'GCT': {'A': '2.520'}, 
             'GCC': {'A': '1.294'}, 
             'GCA': {'A': '0.161'}, 
             'GCG': {'A': '0.025'}, 
             'TGT': {'C': '1.422'}, 
             'TGC': {'C': '0.578'}, 
             'GAT': {'D': '0.645'}}

I want to extract per group max value, like 'A' is 2.520, so I tried:

max(float(x['A']) for x in input_dic.values())

However, it said KeyError: 'A'. I think that this occurs because this key is not unique, but I have no idea how to fix it.

I tried a new method to build the dictionary like

{('A', 'GCT'): '2.520', 
 ('A', 'GCC'): '1.294', 
 ('A', 'GCA'): '0.161', 
 ('A', 'GCG'): '0.025', 
 ('C', 'TGT'): '1.422', 
 ('C', 'TGC'): '0.578', 
 ('D', 'GAT'): '0.645'}

but I also have no idea to extract group 'A' is 2.520. Please tell me if you know how to do it.

like image 876
Katniss Dong Avatar asked Dec 20 '25 18:12

Katniss Dong


1 Answers

Verify that the 'A' key exists in x before keying in:

max(float(x['A']) for x in input_dic.values() if 'A' in x)
like image 102
ggorlen Avatar answered Dec 23 '25 06:12

ggorlen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!