python tuple to dict

前端 未结 6 658
無奈伤痛
無奈伤痛 2020-11-27 10:17

For the tuple, t = ((1, \'a\'),(2, \'b\')) dict(t) returns {1: \'a\', 2: \'b\'}

Is there a good way to get {\'a\': 1, \'

相关标签:
6条回答
  • 2020-11-27 10:32

    Here are couple ways of doing it:

    >>> t = ((1, 'a'), (2, 'b'))
    
    >>> # using reversed function
    >>> dict(reversed(i) for i in t)
    {'a': 1, 'b': 2}
    
    >>> # using slice operator
    >>> dict(i[::-1] for i in t)
    {'a': 1, 'b': 2}
    
    0 讨论(0)
  • 2020-11-27 10:35

    Even more concise if you are on python 2.7:

    >>> t = ((1,'a'),(2,'b'))
    >>> {y:x for x,y in t}
    {'a':1, 'b':2}
    
    0 讨论(0)
  • 2020-11-27 10:40

    Try:

    >>> t = ((1, 'a'),(2, 'b'))
    >>> dict((y, x) for x, y in t)
    {'a': 1, 'b': 2}
    
    0 讨论(0)
  • 2020-11-27 10:40

    If there are multiple values for the same key, the following code will append those values to a list corresponding to their key,

    d = dict()
    for x,y in t:
        if(d.has_key(y)):
            d[y].append(x)
        else:
            d[y] = [x]
    
    0 讨论(0)
  • 2020-11-27 10:44
    >>> dict([('hi','goodbye')])
    {'hi': 'goodbye'}
    

    Or:

    >>> [ dict([i]) for i in (('CSCO', 21.14), ('CSCO', 21.14), ('CSCO', 21.14), ('CSCO', 21.14)) ]
    [{'CSCO': 21.14}, {'CSCO': 21.14}, {'CSCO': 21.14}, {'CSCO': 21.14}]
    
    0 讨论(0)
  • 2020-11-27 10:54

    A slightly simpler method:

    >>> t = ((1, 'a'),(2, 'b'))
    >>> dict(map(reversed, t))
    {'a': 1, 'b': 2}
    
    0 讨论(0)
提交回复
热议问题