Can't unpack values of dictionary with ** - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Can't unpack values of dictionary with ** (/thread-24932.html) |
Can't unpack values of dictionary with ** - Snake - Mar-11-2020 I've seen similar examples in 4.7.5 Unpacking argument lists, but my somehow don't work. >>> d={'USA':'Washington','France':'Paris','China':'Beijing'} >>> **d SyntaxError: invalid syntaxAlso: >>> def f(a,b,c): print(a,b,c) >>> f(**d) Traceback (most recent call last): File "<pyshell#33>", line 1, in <module> f(**d) TypeError: f() got an unexpected keyword argument 'USA' RE: Can't unpack values of dictionary with ** - ndc85430 - Mar-11-2020 The keys in the dict need to match the parameter names of the function. RE: Can't unpack values of dictionary with ** - buran - Mar-11-2020 your function expects only positional arguments and you try to pass keyword arguments it doesn't expect, thus the error. If you pass keyword arguments they need to be present in the function signature. However if keyword arguments present in the function signature you can [almost ever] pass them also as positional arguments (it's possible to force that function take only positional or only keyword arguments). e.g. def greet(name='John', familly='Doe'): print(f'Hello, {name} {familly}') user = {'name': 'Harry', 'familly': 'Potter'} greet(**user) greet(name='Hermione', familly='Granger') greet('Ron', 'Weasley') greet() In addition, your use case does not really warrant use of multiple keyword arguments. Do you really want to have close to 200 arguments? It would be better to pass the dict as single argumentdef print_capitals(capitals=None): if capitals: for country, capital in capitals.items(): print(f'Capital of {country} is {capital}') else: print("Youd didn't supply capitals") my_dict = {'USA':'Washington','France':'Paris','China':'Beijing'} print_capitals() print_capitals(capitals=my_dict) Now, there is a way to take arbitrary number of positional and keyword arguments.def some_func(*args, **kwargs): print(f'Positional arguments: {args}') print(f'Keyword arguments: {kwargs}') print('--------------\n') pos = {'foo', 'bar'} keyw = {'spam':1, 'eggs':2} some_func('foo', spam=1) some_func('foo', 'bar', spam=1, eggs=2) some_func(*pos) some_func(**keyw) some_func('foo', **keyw) some_func(*pos, **keyw) Note, args and kwargs are just names used by convention, they can be different
RE: Can't unpack values of dictionary with ** - Snake - Mar-11-2020 Got it. Thanks guys. |