英文:
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')
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论