KeyError when finding for max value in nested dictionary

1951 views python

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.

answered question

1 Answer


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)

posted this

Have an answer?


Please login first before posting an answer.