python合并字典的2种方式

 

python合并字典2种方式分别为,使用内置方法 update,和关键字参数操作

一 内置方法

a = {1:2}
b = {3:4}


a.update(b)
print(a)

二 **a操作-关键字参数

a = {1:2}
b = {3:4}


c = {**a,**b}
print(c)

第一种是改变a字典

第二种是生成新的字典c。

补充说明: *params 指讲所有值放置在同一个元组中。

三 进一步思考

**a是什么?

从下面资料不难看出,用于函数调用时的传参和构建字典。

In a function call

*t means "treat the elements of this iterable as positional arguments to this function call."

def foo(x, y):
    print(x, y)

>>> t = (1, 2)
>>> foo(*t)
1 2

Since v3.5, you can also do this in a list/tuple/set literals:

>>> [1, *(2, 3), 4]
[1, 2, 3, 4]

**d means "treat the key-value pairs in the dictionary as additional named arguments to this function call."

def foo(x, y):
    print(x, y)

>>> d = {'x':1, 'y':2}
>>> foo(**d)
1 2

Since v3.5, you can also do this in a dictionary literals:

>>> d = {'a': 1}
>>> {'b': 2, **d}
{'b': 2, 'a': 1}

In a function signature

*t means "take all additional positional arguments to this function and pack them into this parameter as a tuple."

def foo(*t):
    print(t)

>>> foo(1, 2)
(1, 2)

**d means "take all additional named arguments to this function and insert them into this parameter as dictionary entries."

def foo(**d):
    print(d)

>>> foo(x=1, y=2)
{'y': 2, 'x': 1}

In assignments and for loops

*x means "consume additional elements in the right hand side", but it doesn't have to be the last item. Note that x will always be a list:

>>> x, *xs = (1, 2, 3, 4)
>>> x
1
>>> xs
[2, 3, 4]

>>> *xs, x = (1, 2, 3, 4)
>>> xs
[1, 2, 3]
>>> x
4

>>> x, *xs, y = (1, 2, 3, 4)
>>> x
1
>>> xs
[2, 3]
>>> y
4

>>> for (x, *y, z) in [ (1, 2, 3, 4) ]: print(x, y, z)
...
1 [2, 3] 4

Note that parameters that appear after a * are keyword-only:

def f(a, *, b): ...

f(1, b=2)  # fine
f(1, 2)    # error: b is keyword-only

Python3.8 added positional-only parameters, meaning parameters that cannot be used as keyword arguments. They are appear before a / (a pun on * preceding keyword-only args).

def f(a, /, p, *, k): ...

f(  1,   2, k=3)  # fine
f(  1, p=2, k=3)  # fine
f(a=1, p=2, k=3)  # error: a is positional-only
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值