Python dictionary creation syntax

前端 未结 7 1820
时光取名叫无心
时光取名叫无心 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 18:51

    Code golf?

    yesindices = [1,2,3,22,34,33]
    noindices = [4,8,9]
    dict (zip(yesindices, ['yes' for i in yesindices]) + zip(noindices, ['no' for i in noindices]))
    

    yields

    {1: 'yes', 2: 'yes', 3: 'yes', 4: 'no', 33: 'yes', 8: 'no', 9: 'no', 34: 'yes', 22: 'yes'}
    
    0 讨论(0)
  • 2020-12-30 18:53

    Try to iterate through the dict items.

    • For python 2.x

    {key: value for key, value in your_dict.iteritems()}

    • For python 3.x

    {key: value for key, value in your_dict.items()}

    0 讨论(0)
  • 2020-12-30 18:55
    d = {'READY': 'GPLR2_95',
        95: 'GPLR2_95',
        'CHARGING': 'GPLR3_99',
        'PROTECTION': 'GPLR3_100',
        'CONNECTED': 'GPLR3_101',
        'ERROR':'GPLR3_102'}
    

    What's wrong with breaking this into multiple lines (as above)? Is the point saving typing or saving vertical space? Something else?

    BTW, it feels really strange to have keys that are a mix of numbers and strings.

    note: I wrote this as an answer instead of a comment because I wanted to show formatted code on multiple lines.

    0 讨论(0)
  • 2020-12-30 18:55
    dict((x, {4: 'no'}.get(x, 'yes')) for x in range(1, 5))
    

    Or in 3.x:

    {x: {4: 'no'}.get(x, 'yes') for x in range(1, 5)}
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-30 19:06

    You could turn it around:

    >>> d1 = {"yes": [1,2,3], "no": [4]}
    

    and then "invert" that dictionary:

    >>> d2 = {value:key for key in d1 for value in d1[key]}
    >>> d2
    {1: 'yes', 2: 'yes', 3: 'yes', 4: 'no'}
    
    0 讨论(0)
提交回复
热议问题