0

有很多个字典要合并,然后进行遍历,我是这样写的:

#!/usr/bin/python3


from collections import ChainMap

dict1={'a':'1','b':'2'}
dict2={'c':'3','d':'4'}
dict3={'e':'5','f':'6'}

newDict=ChainMap(dict1,dict2,dict3)


def map_dict():
    for k, v in newDict.items():
        print(v)
        
        

报错

    for k, v in newDict.items():
  File "/usr/local/python3/lib/python3.6/_collections_abc.py", line 744, in __iter__
    yield (key, self._mapping[key])
  File "/usr/local/python3/lib/python3.6/collections/__init__.py", line 882, in __getitem__
    return mapping[key]             # can't use 'key in mapping' with defaultdict
TypeError: 'dict_items' object is not subscriptable

问题:
应该怎样合并和遍历字典?

2个回答

1

已采纳

我用的是python3.6,这么写是对的啊:

from collections import ChainMap

dict1={'a':'1','b':'2'}
dict2={'c':'3','d':'4'}
dict3={'e':'5','f':'6'}

newDict=ChainMap(dict1,dict2,dict3)


def map_dict():
    for k, v in newDict.items():
        print(k, v)

map_dict()

btw,楼主如果不需要合并后的字典会随着dict1, dict2, dict3的改变而动态改变的话,可以不需要用ChainMap, 直接用dict然后update合并就好了~

1

首先dict的key值是唯一的,所以可以直接使用dict带的update方法
dict1 = {'a': '1', 'b': '2'}
dict2 = {'c': '3', 'd': '4'}
dict3 = {'e': '5', 'f': '6'}

dict_combine = dict1.copy()
dict_combine.update(dict2,)
dict_combine.update(dict3)
print(dict_combine)

撰写答案