11

我正在尝试创建一个可以接收许多或几个字典作为输入的函数。我正在使用以下代码:

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, in <module>
main_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'

任何人都可以启发我的旅程?

4

5 回答 5

13

使用任意参数列表,可以使用任意数量的参数调用函数:

>>> 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)}
于 2015-12-13T13:12:25.563 回答
6

您应该尝试 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
于 2015-12-13T13:02:30.613 回答
4

这是基于@falsetru 答案并使用该operator.and_函数的 Python 3.x 答案。

>>> from functools import reduce
>>> import operator
>>> def merge_many_dicts(*dicts):
...     common_keys = reduce(operator.and_, (d.keys() for d in dicts))
...     return {key: tuple(d[key] for d in dicts) for key in common_keys}
... 
>>> merge_many_dicts({1:2}, {1:3}, {1:4, 2:5})
{1: (2, 3, 4)}
于 2015-12-13T13:26:50.700 回答
0

正如错误所说,您无法查看布尔值的键,也就是 True.viewkeys() 不起作用。将默认字典更改为空,留下:

def merge_many_dics(dic1,dic2,dic3={},dic4={},dic5={},dic6={},dic7={},dic8={},dic9={},dic10={}):
    """
    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

这是一个实现,您可以在其中为每个键创建一个列表并添加每个项目,我相信它可以进行更多优化,但它非常易读:

def merge_many_dicts(*args):
    """
    Merging all dictionaries suposing all dictionaries share keys
    :return: a dictionary containing the common dates as keys and both values as values
    """
    manydicts = {}
    for k in args:
        for key in k.iterkeys():
            manydicts[key] = []
    for k in args:
        for key, value in k.iteritems():
            manydicts[key].append(value)

    return manydicts
于 2015-12-13T13:05:35.180 回答
0

您可以使用以下代码在函数中初始化这些参数

def merge_many_dics(dic1, dic2, dic3=None, dic4=None, dic5=None, dic6=None, dic7=None, dic8=None, dic9=None,
                    dic10=None):
    """
    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
    """
    for item in locals().items():
        if item is None:
            item = dic1

    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
于 2015-12-13T13:13:16.693 回答