python3函数无法连接python词典

2024-09-28 20:54:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我总是得到一本空字典

#!/usr/local/bin/python3


dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
dictNew = {}


def concatDict(dictCon):
    dictNew = dict.update(dictCon)
    return dictNew


concatDict(dic1)
concatDict(dic2)
concatDict(dic3)

print(dictNew)

无法从函数调用更新dictNew

有人能给我指出正确的方向吗


Tags: return字典binusrlocaldefupdatedict
3条回答

您可以使用concatDicts函数接受可变数量的dict作为输入,并返回新的合并dict

>>> 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}

对于加入词典,您只需使用以下代码:

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}

您想用dictCon字典参数更新dictNew。由于字典是可变的,您不需要保存或返回结果,因为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}

但是请注意,您的函数实际上只是掩蔽dictNew.update,因此您最好使用该方法调用而不是此包装函数:

...
dictNew.update(dic1)
dictNew.update(dic2)
dictNew.update(dic3)
...

另一种方法是使用**-运算符分解字典:

{**dic1, **dic2, **dic3}

相关问题 更多 >