use*_*677 2 python dictionary tuples function typeerror
我正在尝试创建一个函数,该函数将采用arbritrary数量的字典输入并创建包含所有输入的新字典.如果两个键相同,则该值应为包含两个值的列表.我已经成功完成了这项工作 - 但是,我遇到了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)
Run Code Online (Sandbox Code Playgroud)
我得到的错误如下:
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
Run Code Online (Sandbox Code Playgroud)
如上所述,在python shell中,print(newtlist)给出:
[('Andy', '555-1195'), ('Fred', ['555-1231', '555-1234']), ('John', '555-3195'), ('Karen', '555-2793')]
Run Code Online (Sandbox Code Playgroud)
如果我将此输出复制并粘贴到dict()函数中:
dict([('Andy', '555-1195'), ('Fred', ['555-1231', '555-1234']), ('John', '555-3195'), ('Karen', '555-2793')])
Run Code Online (Sandbox Code Playgroud)
输出成为我想要的,这是:
{'Karen': '555-2793', 'Andy': '555-1195', 'Fred': ['555-1231', '555-1234'], 'John': '555-3195'}
Run Code Online (Sandbox Code Playgroud)
无论我尝试什么,我都无法在我的功能中重现这一点.请帮帮我!谢谢!
关键字不应该用作变量名称的典型示例.这里dict(newtlist)
试图调用dict()
内置python,但是有一个冲突的局部变量dict
.重命名该变量以解决问题.
像这样的东西:
def dictcomb(*dct): #changed the local variable dict to dct and its references henceforth
mykeys = []
myvalues = []
tupl = ()
tuplist = []
newtlist = []
count = 0
for i in dct:
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)
Run Code Online (Sandbox Code Playgroud)