简体   繁体   中英

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?

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,

So either I should forget about dictionaries and write all values insides the function or use dicts and add 20 params in myfunction(inputs)

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....

Use 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

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 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.

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

You can't pass the same kwarg twice.

>>> 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.

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

You can do it without using **kwargs as well.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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