Python 为什么这本词典解包不起作用
以下代码起作用:Python 为什么这本词典解包不起作用,python,python-3.x,Python,Python 3.x,以下代码起作用: >>> stack = ['a','b','c'] >>> top, *stack = stack >>> top 'a' >>> stack ['b', 'c'] 但是为什么这不起作用呢 >>> dict1={'a':1, 'b':2, 'c':3} >>> x, **dict1=dict1 SyntaxError: invalid syntax 我不应
>>> stack = ['a','b','c']
>>> top, *stack = stack
>>> top
'a'
>>> stack
['b', 'c']
但是为什么这不起作用呢
>>> dict1={'a':1, 'b':2, 'c':3}
>>> x, **dict1=dict1
SyntaxError: invalid syntax
我不应该期望x={'a':1}和dict1={'b':2,'c':3}吗?如果希望使用字典解包,可以这样做:(使用Python3.7)
dict1.items()
,以(键,值)
对的形式返回元组列表,其中每个元组包含2个元素。因此,如果您希望将未打包的值转换回字典,则必须执行以下操作->
>>> x = [x] # x = list(x), won't work for you, because it converts tuple into a list.
# What is actually want is the tuple to be an element of the list.
>>> x # And it works like a charm!
[('a', 1)]
但是,当打开元组列表时,dict1
包含长度为2的列表,这两个列表都是元组。因此,将其转换为词典是一种相当简单的方法
>>> dict1
[('b', 2), ('c', 3)]
>>> dict1 = dict(dict1)
>>> dict1
{'b': 2, 'c': 3}
因为运算符
**
只能用于在函数调用中将字典解包为关键字参数。例如,您可以使用函数dict()
合并两个dict,该函数的参数为**kwargs
:
a = {'a': 1, 'b': 2}
b = {'c': 3, 'd': 4}
print(dict(**a, **b))
# {'a': 1, 'b': 2, 'c': 3, 'd': 4}
在元组解包中不能像使用单星一样使用双星。字典没有排序,因此先使用
x
并不意味着什么。解包后的字符串列表给出单个字符串,而不是子列表。如果它真的是并行的,一个未打包的dict将给出单独的键值项,而不是子项。但是,“a”:1在Python中不是有效的类型。幸运的是,有一种简单的方法可以从dict中获取对:x,*rest=dict1.items()
也可以工作,(k,v),*rest=dict1.items()
。(请注意,正如njzk所说,订单是不保证的)。最好是明确的,并且v=dict1.get('x')
(或者pop
,如果你想从dict中删除)。@Amadan除非你不能保证x
会包含(a,1)
而不是来自dictionary@njzk2:为什么不能从解包dict1中为x分配任何第一个?@techie11,因为dict没有第一个
的概念,因为dict没有排序
a = {'a': 1, 'b': 2}
b = {'c': 3, 'd': 4}
print(dict(**a, **b))
# {'a': 1, 'b': 2, 'c': 3, 'd': 4}