Python dictionary creation syntax

前端 未结 7 1826
时光取名叫无心
时光取名叫无心 2020-12-30 18:25

I\'m wondering if there\'s any way to populate a dictionary such that you have multiple keys mapping to the same value that\'s less verbose than say:

d = {1:         


        
7条回答
  •  [愿得一人]
    2020-12-30 19:02

    For your case

    dict([(_, 'yes') for _ in range(1,4)], **{4:'no'})
    

    And if you need multiple keys for 'yes' and 'no'

    >>> from itertools import chain
    >>> dict(chain([(_, 'yes') for _ in range(1,4)], [(_, 'no') for _ in range(4, 10)]))
    {1: 'yes', 2: 'yes', 3: 'yes', 4: 'no', 5: 'no', 6: 'no', 7: 'no', 8: 'no', 9: 'no'}
    

    Not so great, but works.

提交回复
热议问题