我有一个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
您有一个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'}
首先更正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()}