What's wrong with this dictionary comprehension code?

时光总嘲笑我的痴心妄想 提交于 2020-05-31 04:55:05

问题


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


回答1:


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



回答2:


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()}



来源:https://stackoverflow.com/questions/61906014/whats-wrong-with-this-dictionary-comprehension-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!