【Python 学习笔记】dictionary unpacking

what is dictionary unpacking?

Dictionary unpacking is a Python feature that allows you to extract key-value pairs from a dictionary and:

  1. 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
  2. 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" 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值