convert string to dict using list comprehension

后端 未结 8 1883
情歌与酒
情歌与酒 2021-02-05 12:34

I have came across this problem a few times and can\'t seem to figure out a simple solution. Say I have a string

string = \"a=0 b=1 c=3\"

I wan

相关标签:
8条回答
  • 2021-02-05 13:10

    I sometimes like this approach, especially when the logic for making keys and values is more complicated:

    s = "a=0 b=1 c=3"
    
    def get_key_val(x):
        a,b = x.split('=')
        return a,int(b)
    
    ans = dict(map(get_key_val,s.split()))
    
    0 讨论(0)
  • 2021-02-05 13:10

    I would do this:

    def kv(e): return (e[0], int(e[1]))
    d = dict([kv(e.split("=")) for e in string.split(" ")])
    
    0 讨论(0)
  • 2021-02-05 13:17

    Nowadays you should probably use a dictionary comprehension, introduced in 2.7:

    mydict = {key: int(value) for key, value in (a.split('=') for a in mystring.split())}
    

    The dictionary comprehension is faster and shinier (and, in my opinion, more readable).

    from timeit import timeit
    
    setup = """mystring = "a=0 b=1 c=3\""""
    code1 = """mydict = dict((n,int(v)) for n,v in (a.split('=') for a in mystring.split()))""" # S.Lott's code
    code2 = """mydict = {key: int(value) for key, value in (a.split('=') for a in mystring.split())}"""
    
    print timeit(code1, setup=setup, number=10000) # 0.115524053574
    print timeit(code2, setup=setup, number=10000) # 0.105328798294
    
    0 讨论(0)
  • 2021-02-05 13:20

    Do you mean this?

    >>> dict( (n,int(v)) for n,v in (a.split('=') for a in string.split() ) )
    {'a': 0, 'c': 3, 'b': 1}
    
    0 讨论(0)
  • 2021-02-05 13:20

    Try the next:

    dict([x.split('=') for x in s.split()])
    
    0 讨论(0)
  • 2021-02-05 13:25
    from cgi import parse_qsl
    text = "a=0 b=1 c=3"
    dic = dict((k, int(v)) for k, v in parse_qsl(text.replace(' ', '&')))
    print dic
    

    prints

    {'a': 0, 'c': 3, 'b': 1}
    
    0 讨论(0)
提交回复
热议问题