我正在尝试制作一个函数,该函数将采用任意数量的字典输入并创建一个包含所有输入的新字典。如果两个键相同,则该值应该是包含两个值的列表。我已经成功地做到了这一点——但是,我在使用 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'}
无论我尝试什么,我都无法在我的函数中重现它。请帮帮我!谢谢!
最佳答案
为什么不应该使用关键字作为变量名的典型例子。这里 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)
关于python - Python 中的 dict() 问题,TypeError :'tuple' 对象不可调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18241967/