我正在尝试制作一个函数,该函数将采用任意数量的字典输入并创建一个包含所有输入的新字典。如果两个键相同,则值应该是一个包含两个值的列表。我已经成功地做到了——但是,我遇到了 dict() 函数的问题。如果我在 python shell 中手动执行 dict 函数,我可以毫无问题地制作一个新字典;但是,当它嵌入到我的函数中时,我得到一个 TypeError。下面是我的代码:
#Module 6 Written Homework
#Problem 4
dict1= {'Fred':'555-1231','Andy':'555-1195','Sue':'555-2193'}
dict2= {'Fred':'555-1234','John':'555-3195','Karen':'555-2793'}
def dictcomb(*dict):
mykeys = []
myvalues = []
tupl = ()
tuplist = []
newtlist = []
count = 0
for i in dict:
mykeys.append(list(i.keys()))
myvalues.append(list(i.values()))
dictlen = len(i)
count = count + 1
for y in range(count):
for z in range(dictlen):
tuplist.append((mykeys[y][z],myvalues[y][z]))
tuplist.sort()
for a in range(len(tuplist)):
try:
if tuplist[a][0]==tuplist[a+1][0]:
comblist = [tuplist[a][1],tuplist[a+1][1]]
newtlist.append(tuple([tuplist[a][0],comblist]))
del(tuplist[a+1])
else:
newtlist.append(tuplist[a])
except IndexError as msg:
pass
print(newtlist)
dict(newtlist)
我得到的错误如下:
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
dictcomb(dict1,dict2)
File "C:\Python33\M6HW4.py", line 34, in dictcomb
dict(newtlist)
TypeError: 'tuple' object is not callable
如上所述,在 python shell 中, print(newtlist) 给出:
[('Andy', '555-1195'), ('Fred', ['555-1231', '555-1234']), ('John', '555-3195'), ('Karen', '555-2793')]
如果我将此输出复制并粘贴到 dict() 函数中:
dict([('Andy', '555-1195'), ('Fred', ['555-1231', '555-1234']), ('John', '555-3195'), ('Karen', '555-2793')])
输出变成了我想要的,也就是:
{'Karen': '555-2793', 'Andy': '555-1195', 'Fred': ['555-1231', '555-1234'], 'John': '555-3195'}
无论我尝试什么,我都无法在我的函数中重现它。请帮帮我!谢谢!