Search code examples
pythonpython-3.xdictionarydictionary-comprehension

What's wrong with this dictionary comprehension code?


I have a python dictionary which is some kind of a glossary.

glossary_dict = {'AA': 'AA_meaning',
                 'BB': 'BB_meaning',
                 'CC': 'CC_meaning',
                 }

Here is the original dictionary.

original = [{'AA': '299021.000000'},
            {'BB': '299021.000000'},
            {'CC': '131993.000000'},
            ]

I want to replace the keys of original dictionary with the corresponding value of glossary_dict. The final result will look like this;

explained = {'AA_meaning': '299021.000000',
             'BB_meaning': '299021.000000',
             'CC_meaning': '131993.000000',
            } 

I want to solve this problem using dictionary comprehension approach. This is what I did;

explained = {glossary_dict[key]: value for (key, value) in original[0].items()}

The result is {'AA_meaning': '299021.000000'}. It is close but still not the correct answer. What did I miss out?

I am using python 3.7


Solution

  • You have a list of dicts, Iterate the list and then access the key

    Ex:

    explained = {glossary_dict[key]: value for i in original for key, value in i.items()}
    print(explained)
    

    Output:

    {'AA_meaning': '299021.000000',
     'BB_meaning': '299021.000000',
     'CC_meaning': '131993.000000'}