what is dictionary unpacking?
Dictionary unpacking is a Python feature that allows you to extract key-value pairs from a dictionary and:
-
Pass them as arguments to a function using
**
def greet(name, age): print(f"Hello, my name is {name} and I'm {age} years old.") person = {"name": "Alice", "age": 30} greet(**person) # Unpacks keys as argument names
-
Merge dictionaries / Create new dictionaries from existing ones
defaults = {"color": "blue", "size": "medium"}
custom = {"size": "large"}
combined = {**defaults, **custom}
print(combined) # {'color': 'blue', 'size': 'large'}
dict1 = {"a": 1}
dict2 = {"b": 2}
new_dict = {**dict1, **dict2, "c": 3}
print(new_dict) # {'a': 1, 'b': 2, 'c': 3}
-
**
is used to unpack a dictionary's key-value pairs: -
It's useful for function calls and dictionary composition
"Answer Generated by OpenAI's ChatGPT"