我正在尝试创建一个可能作为输入接收多个或几个字典的函数.我正在使用以下代码:
def merge_many_dics(dic1,dic2,dic3=True,dic4=True,dic5=True,dic6=True,dic7=True,dic8=True,dic9=True,dic10=True): """ Merging up to 10 dictionaries with same keys and different values :return: a dictionary containing the common dates as keys and both values as values """ manydics = {} for k in dic1.viewkeys() & dic2.viewkeys() & dic3.viewkeys() & dic4.viewkeys() & dic5.viewkeys() & dic6.viewkeys()\ & dic7.viewkeys() & dic8.viewkeys() & dic9.viewkeys() & dic10.viewkeys(): manydics[k] = (dic1[k], dic2[k],dic3[k],dic4[k],dic5[k],dic6[k],dic7[k],dic8[k],dic9[k],dic10[k]) return manydics
请注意,我试图将参数dic3,dic4,dic5等等于"True",因此当它们未被指定并且在函数中被调用时,没有任何反应.但是我收到以下错误:
Traceback (most recent call last): File "/Users/File.py", line 616, inmain_dic=merge_many_dics(dic1,dic2,dic3,dic4) File "/Users/File.py", line 132, in merge_many_dics & dic7.viewkeys() & dic8.viewkeys() & dic9.viewkeys() & dic10.viewkeys(): AttributeError: 'bool' object has no attribute 'viewkeys'
有人为我的旅程提供服务吗?
使用任意参数列表,可以使用任意数量的参数调用该函数:
>>> def merge_many_dics(*dicts): ... common_keys = reduce(lambda a, b: a & b, (d.viewkeys() for d in dicts)) ... return {key: tuple(d[key] for d in dicts) for key in common_keys} ... >>> merge_many_dics({1:2}, {1:3}, {1:4, 2:5}) {1: (2, 3, 4)}
你应该尝试args语法:
def merge_many_dics(*args): iterate over your args to join them
然后你可以使用任意数量的参数调用函数.
带*args的函数可以如下:
def print_all(name, *args): print "Hello", name, "here are your args" for arg in args: print arg print_all("Claus", "car", "boat", "house")
这将打印:
Hello Clause here are your args car boat house