这个字典理解码怎么了?

问题描述 投票:1回答:2

我有一个python字典,有点像词汇表。

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

这是原始词典。

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

我想用相应的original值替换glossary_dict词典的键。最终结果将如下所示;

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

我想使用字典理解方法解决此问题。这就是我所做的;

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

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

我正在使用python 3.7

python python-3.x dictionary dictionary-comprehension
2个回答
4
投票

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

Ex:

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

1
投票

首先更正explained词典。然后,使用,

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

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

然后,

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

© www.soinside.com 2019 - 2024. All rights reserved.