我试着总结两本词典这样的:类型错误:不支持的操作数类型(S)为+: 'dict_items' 和 'dict_items'
my_new_dict = dict(my_existing_dict.items() + my_new_dict.items())
但收到错误
TypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items'
我做什么错误?
我试着总结两本词典这样的:类型错误:不支持的操作数类型(S)为+: 'dict_items' 和 'dict_items'
my_new_dict = dict(my_existing_dict.items() + my_new_dict.items())
但收到错误
TypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items'
我做什么错误?
在python3,dict.items()
返回与这显然不能被添加dict_items
类型的对象。 (在Python 2中,它返回了list
,可以添加它)。
的另一种方式增加对字典的这对py2k和py3k工作:
d = dict1.copy()
d.update(dict2)
当然,还有你想在关键的碰撞的情况下发生的事情有些含糊不清。例如如果两个字典都有key1
,其key1
应该保留在输出中?或者你应该使用它们的两个值的组合?在后一种情况下,你可能会想从collections
模块的东西(无论是defaultdict
或Counter
)
谢谢,它的作品!我讨厌2.7> 3.2迁移... – JohnDow
@ VladislavIl'ushin:你真的**应该阅读文档。 – SilentGhost
@mgilson:我认为3+中的'dict.items()'等同于2.6中的'dict.iteritems()',也就是说它是一个迭代器。 –
第一个问题是这是模棱两可的 - 词典不能有重复的键,所以你不清楚你的意思,如果两者都包含相同的键,会发生什么?
但是,这里的主要问题是dictionary views are set-like,所以他们没有添加实现。
你可能想要的是union:d1.items() | d2.items()
,它会给你一套(key, value)
的元组。如果您将其传递给dict()
并且有重复项,则最后一个值将是使用的值。
因此,简而言之:
dict(d1.items() | d2.items())
当我尝试这个时,我得到:'TypeError:unhashable type:'dict'' –
lifesaver!好戏,我的朋友! –
旁注:如果你想遍历两个字典,你知道他们有独特的键(或者它并不重要,如果你处理相同的密钥两次),考虑使用itertools.chain(dict_a,dict_b) – Moberg