Dictionary unpacking in python Python中的字典解包

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

Dictionary unpacking in python

问题

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

  1. i_ate = {'apple': 2, 'beetroot': 0, 'cinnamon': 3, 'donut': 8}
  2. # Elaborate
  3. apples = i_ate['apple']
  4. rest = {k: v for k, v in i_ate.items() if k != 'apple'}
  5. # Shortcut
  6. apples, rest = i_ate['apple'], {k: v for k, v in i_ate.items() if k != 'apple'}
  7. # Result in both cases:
  8. apples # 2
  9. 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:

  1. i_ate = ['apple', 'beetroot', 'cinnamon', 'donut']
  2. # Elaborate
  3. first = i_ate[0]
  4. rest = [item for j, item in enumerate(i_ate) if j != 0]
  5. # Shortcut
  6. first, *rest = i_ate
  7. # Result in both cases:
  8. first # 'apple'
  9. rest # ['beetroot', 'cinnamon', 'donut']

Does someting similar exist for dictionaries?

  1. i_ate = {'apple': 2, 'beetroot': 0, 'cinnamon': 3, 'donut': 8}
  2. # Elaborate
  3. apples = i_ate['apple']
  4. rest = {k: v for k, v in i_ate.items() if k != 'apple'}
  5. # Shortcut??
  6. # -- Your line of code here --
  7. # Result in both cases:
  8. apples # 2
  9. 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:

  1. _, *rest = i_ate.items()
  2. dict(rest)
  3. {'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:

  1. (_, first_val), *rest = i_ate.items()
  2. first_val
  3. 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

  1. >>> _, *rest = i_ate.items()
  2. >>> dict(rest)
  3. {'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:

  1. >>> (_, first_val), *rest = i_ate.items()
  2. >>> first_val
  3. 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:

确定