我想合并下面这两个字典的内容。
>>> key_dict
{
'1': 'seq',
'0': 'seq',
'2': 'seq'
}
>>> value_dict
{
'tedious; repetitive and boring': 'text',
'worldly': 'text',
'ordinary': 'text'
}
因此,在最终列表中,我有类似以下内容的东西
>>>final_list
[
{
'seq': 0,
'text': 'worldly'
},
{
'seq': 1,
'text': 'tedious; repetitive and boring'
},
{
'seq': 2,
'text': 'ordinary'
}
]
编辑:抱歉,我尝试了这个
>>> final_list = []
>>> temp_dict = {}
>>> for (key1, value1), (key2, value2) in zip(key_dict.items(), value_dict.items()):
... temp_dict[value1] = key1
... temp_dict[value2] = key2
... final_list.append[temp_dict]
...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
TypeError: 'builtin_function_or_method' object is not subscriptable
>>>
请问我哪里出了问题,需要帮助。
编辑2:
更正后,将final_list.append[temp_dict]
改为final_list.append(temp_dict)
我得到了这个结果
>>> pprint(final_list)
[{'seq': '1', 'text': 'ordinary'},
{'seq': '1', 'text': 'ordinary'},
{'seq': '1', 'text': 'ordinary'}]
>>>
有人能解释一下为什么值会被重复,我无法理解。
OrderedDict
。 - JRodDynamitefinal_list.append[temp_dict]
应该修改为final_list.append(temp_dict)
。 - Paul Rooney