3 回答
TA贡献1777条经验 获得超3个赞
要加入字典,您只需使用以下代码:
dict1 = {1: 10, 2: 20}
dict2 = {3: 30, 4: 40}
dict3 = {5: 50, 6: 60}
dict_new = {**dic1, **dic2, **dic3}
print(dict_new)
结果:
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
TA贡献1836条经验 获得超4个赞
您可以让您的concatDicts函数接受可变数量的字典作为输入并返回一个新的合并字典
>>> dic1 = {1:10, 2:20}
>>> dic2 = {3:30, 4:40}
>>> dic3 = {5:50, 6:60}
>>>
>>> def concatDicts(*dicts):
... return dict((k,v) for dic in dicts for k,v in dic.items())
...
>>>
>>> new_dic = concatDicts(dic1, dic2, dic3)
>>> print(new_dic)
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
TA贡献1883条经验 获得超3个赞
您想dictNew使用dictCon字典参数进行更新。由于字典是可变的,因此您不需要保存或返回dictNew将被改变的结果:
#!/usr/local/bin/python3
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
dictNew = {}
def concatDict(dictCon):
dictNew.update(dictCon)
concatDict(dic1)
concatDict(dic2)
concatDict(dic3)
print(dictNew)
这使:
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
但是请注意,您的函数实际上只是 masking dictNew.update,因此您最好使用该方法调用而不是此包装函数:
...
dictNew.update(dic1)
dictNew.update(dic2)
dictNew.update(dic3)
...
另一种方法是使用**-operator 来分解字典:
{**dic1, **dic2, **dic3}
添加回答
举报