使用字典作为可选参数的函数 - Python

时间:2015-12-13 12:59:11

标签: python dictionary optional-arguments

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

var hometeam_goal = document.getElementById("add_goal_hometeam");

hometeam_goal.addEventListener("mousedown", function homegoal_md (event) {
    mouse_start = Date.now();
}

hometeam_goal.addEventListener("mouseup", function homegoal_mu (event) {
    mouse_delta = Date.now() - mouse_start;
    if (mouse_delta < foo) {
        <do something>
    }
}

请注意,我试图将参数dic3,dic4,dic5等等于“True”,所以当它们未被指定并且在函数中被调用时,没有任何反应。但是我收到以下错误:

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

任何人都可以参加我的旅程吗?

5 个答案:

答案 0 :(得分:13)

使用arbitrary argument list,可以使用任意数量的参数调用该函数:

>>> 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)}

答案 1 :(得分: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

答案 2 :(得分: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)}

答案 3 :(得分: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

答案 4 :(得分: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