【发布时间】:2015-11-30 05:29:54
【问题描述】:
我想合并以下两个字典的内容
>>> 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。 -
我应该将值作为元组传递给
dicts 吗? -
解决你的即时错误
final_list.append[temp_dict]应该是final_list.append(temp_dict) -
@PaulRooney Dang。我在问题中添加了输出
标签: python list python-3.x dictionary