Disclaimer: I am new to Python.
If you read this article, it lists **
as being able to unpack dictionaries. I was trying this out.
my_dict = {"key1": 1, "key2": {"inner_key": 3} }
unpacked_dict = **my_dict
Returns: SyntaxError: invalid syntax
What am I missing? I know **
is used mainly with **kwargs
, is my problem that **
can only be used in a function definition?
You can use it to unpack it into other dictionaries. It doesn't work in the way I assume you are trying to do it which is taken inner dictionaries from values and make them all part of the same level. From the article you referenced:
For example we can copy a dictionary while adding a new value to it:
>>> date_info = {'year': '2020', 'month': '01', 'day': '7'} >>> event_info = {**date_info, 'group': "Python Meetup"} >>> event_info {'year': '2020', 'month': '01', 'day': '7', 'group': 'Python Meetup'}
Or copy/merge dictionaries while overriding particular values:
>>> event_info = {'year': '2020', 'month': '01', 'day': '7', 'group': 'Python Meetup'} >>> new_info = {**event_info, 'day': "14"} >>> new_info {'year': '2020', 'month': '01', 'day': '14', 'group': 'Python Meetup'}
This was added as of Python 3.5+, more info is in PEP 448.