此字典理解代码有什么问题? [英] What's wrong with this dictionary comprehension code?

查看:67
本文介绍了此字典理解代码有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本类似词汇表的python字典。

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

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

这是原始词典。

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

我想将原始词典的键替换为相应的 glossary_dict
最终结果将如下所示:

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

结果为 {'AA_意义':'299021.000000 '} 。这很接近,但仍然不是正确的答案。我错过了什么?

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

我正在使用python 3.7

I am using python 3.7

推荐答案

您有一个 dict s的列表,迭代该列表,然后访问密钥

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

例如:

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

输出:

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

这篇关于此字典理解代码有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆