Dictionary unpacking in python Python中的字典解包

huangapple go评论70阅读模式
英文:

Dictionary unpacking in python

问题

For dictionaries, you can achieve a similar result using the following code:

i_ate = {'apple': 2, 'beetroot': 0, 'cinnamon': 3, 'donut': 8}

# Elaborate
apples = i_ate['apple']
rest = {k: v for k, v in i_ate.items() if k != 'apple'}

# Shortcut
apples, rest = i_ate['apple'], {k: v for k, v in i_ate.items() if k != 'apple'}

# Result in both cases:
apples # 2
rest # {'beetroot': 0, 'cinnamon': 3, 'donut': 8}

Is there anything else you'd like to know or translate?

英文:

For a list, I can split it with one compact line of code:

i_ate = ['apple', 'beetroot', 'cinnamon', 'donut']

# Elaborate
first = i_ate[0]
rest = [item for j, item in enumerate(i_ate) if j != 0]

# Shortcut
first, *rest = i_ate

# Result in both cases:
first # 'apple'
rest # ['beetroot', 'cinnamon', 'donut']

Does someting similar exist for dictionaries?

i_ate = {'apple': 2, 'beetroot': 0, 'cinnamon': 3, 'donut': 8}

# Elaborate
apples = i_ate['apple']
rest = {k: v for k, v in i_ate.items() if k != 'apple'}

# Shortcut??
# -- Your line of code here --

# Result in both cases:
apples # 2
rest # {'beetroot': 0, 'cinnamon': 3, 'donut': 8}

答案1

得分: 3

How about unpacking the dict as items? This will work on any python version that supports ordered dicts:

_, *rest = i_ate.items()
dict(rest)
{'beetroot': 0, 'cinnamon': 3, 'donut': 8}

As slothrop in the comments suggested, if first_value is also needed, the first item can further be unpacked:

(_, first_val), *rest = i_ate.items()
first_val
2

.items() converts the dictionary into a sequence of tuples.

Alternatively, just delete the entry you don't want in-place using del i_ate['apple'] or i_ate.pop('apple').

英文:

How about unpacking the dict as items? This will work on any python version that supports ordered dicts

>>> _, *rest = i_ate.items()
>>> dict(rest)
{'beetroot': 0, 'cinnamon': 3, 'donut': 8}

As slothrop in the comments suggested, if first_value is also needed, the first item can further be unpacked:

>>> (_, first_val), *rest = i_ate.items()
>>> first_val
2

.items() converts the dictionary into a sequence of tuples

Alternatively, just delete the entry you don't want in-place using del i_ate['apple'] or i_ate.pop('apple').

huangapple
  • 本文由 发表于 2023年4月13日 21:30:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76006042.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定