user3848207
user3848207

Reputation: 4927

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

Upvotes: 1

Views: 54

Answers (2)

Abhishek Verma
Abhishek Verma

Reputation: 1729

Correct your explained dictionary first. Then, use,

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

to

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

Then,

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

Upvotes: 1

Rakesh
Rakesh

Reputation: 82765

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'}

Upvotes: 4

Related Questions