简体   繁体   English

python-如何在不重复字典中的元素的情况下将字典作为 function 中的输入传递

[英]python-how to pass dictionaries as inputs in function without repeating the elements in dictionary

How I can pass the dictionaries as an input of a function without repeating the elements in function?如何在不重复 function 中的元素的情况下将字典作为 function 的输入传递?

please see a simplified example below:请看下面的简化示例:

def myfuction(a,b,c):
    aa = b/2
    y = a+b+c+aa 
    return y

dict_1 = {'a':1,'b':2}
dict_2 = {'c':3}

myfuction(**dict_1, **dict_2)

The problem is that each dict in my code has 10 elements,问题是我的代码中的每个 dict 都有 10 个元素,

So either I should forget about dictionaries and write all values insides the function or use dicts and add 20 params in myfunction(inputs)所以要么我应该忘记字典并将所有值写入 function 或使用字典并在 myfunction(inputs) 中添加 20 个参数

What is the best way to unpack parameters without repeating them.在不重复参数的情况下解压缩参数的最佳方法是什么。

def myfuction(a=0,b=0,c=0):
    aa = b/2
    y = a+b+c+aa 
    return y

dict_1 = {'a':1,'b':2}
dict_2 = {'c':3}

print(myfuction(**dict_1, **dict_2))
# 7

...the best way... is going to be subjective.... ...the best way...将是主观的......

Use kwargs :使用kwargs

def myfuction(**kwargs):
    aa = kwargs['b']/2
    y = kwargs['a'] + kwargs['b'] + kwargs['c'] + aa 
    return y

Using a namedtuple使用命名元组

import collections
def myfuction(**kwargs):
    D = collections.namedtuple('D',field_names=kwargs.keys(),defaults=kwargs.values())
    d = D()
    aa = d.b/2
    y = d.a + d.b + d.c + aa 
    return y

Using function attributes使用 function 属性

def myfuction(**kwargs):
    for k,v in kwargs.items():
        setattr(myfuction,k,v)
    aa = myfuction.b/2
    y = myfuction.a + myfuction.b + myfuction.c + aa 
    return y

Or a class and do the same setattr trick或 class 并执行相同的setattr技巧

class D:
    pass
def myfuction(**kwargs):
    d = D()
    for k,v in kwargs.items():
        setattr(d,k,v)
    aa = d.b/2
    y = d.a + d.b + d.c + aa 
    return y

# OR put the attribute part in the class
class D:
    def __init__(self,dictionary):
        for k,v in dictionary.items():
            setattr(self,k,v)
def myfuction(**kwargs):
    d = D(kwargs)
    aa = d.b/2
    y = d.a + d.b + d.c + aa 
    return y

Your example is confusing because it isn't correct code.您的示例令人困惑,因为它不是正确的代码。 You need to get the value from the dictionary.您需要从字典中获取值。

def myfunction(d1, d2)
    aa = d1['b'] / 2
    y = d1['a'] + d1['b'] + d2['c'] + aa

Perhaps, this is the problem you are facing.也许,这就是你面临的问题。 I have a sample function to demonstrate this.我有一个示例 function 来证明这一点。

>>> def f(**kw):
...   print(kw)

You can't pass the same kwarg twice.你不能两次通过同一个 kwarg。

>>> f(a=10, b=20, a=30)
  File "<stdin>", line 1
SyntaxError: keyword argument repeated

You can't do it by unpacking if the unpacked dicts have common keys.如果解包的字典有公共键,你不能通过解包来做到这一点。

>>> d1 = {'a': 1, 'b': 2}
>>> d2 = {'b': 3, 'c': 4}
>>> f(**d1, **d2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: f() got multiple values for keyword argument 'b'

However, you can create a new dict and unpack that instead to pass to the function.但是,您可以创建一个新的 dict 并解压缩,而不是传递给 function。

>>> f(**{**d1, **d2})
{'a': 1, 'b': 3, 'c': 4}

You can do it without using **kwargs as well.您也可以在不使用**kwargs的情况下做到这一点。

>>> def g(a, b, c):
...   print(f'{a=}, {b=}, {c=}')
... 
>>> g(**{**d1, **d2})
a=1, b=3, c=4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM