Creating a dictionary from a string

前端 未结 7 1951
轻奢々
轻奢々 2020-12-08 17:02

I have a string in the form of:

s = \'A - 13, B - 14, C - 29, M - 99\'

and so on (the length varies). What is the easiest way to create a d

相关标签:
7条回答
  • 2020-12-08 17:13

    This should work:

    dict(map(lambda l:map(lambda j:j.strip(),l), map(lambda i: i.split('-'), s.split(','))))
    

    If you don't want to strip, just do:

    dict(map(lambda i: i.split('-'), s.split(',')))
    
    0 讨论(0)
  • 2020-12-08 17:16

    Those who came here with following problem :

    convert string a = '{"a":1,"b":2}' to dictionary object.

    you can simply use a = eval(a) to get a as object of dictionary from a string object.

    0 讨论(0)
  • 2020-12-08 17:17
    >>> dict((k.strip(),int(v.strip())) for k,v in (p.split('-') for p in s.split(',')))
    {'A': 13, 'B': 14, 'M': 99, 'C': 29}
    
    0 讨论(0)
  • 2020-12-08 17:19
    >>> s = 'A - 13, B - 14, C - 29, M - 99'
    >>> dict(e.split(' - ') for e in s.split(','))
    {'A': '13', 'C': '29', 'B': '14', 'M': '99'}
    

    EDIT: The next solution is for when you want the values as integers, which I think is what you want.

    >>> dict((k, int(v)) for k, v in (e.split(' - ') for e in s.split(',')))
    {'A': 13, ' B': 14, ' M': 99, ' C': 29}
    
    0 讨论(0)
  • 2020-12-08 17:20

    To solve your example you can do this:

    mydict = dict((k.strip(), v.strip()) for k,v in 
                  (item.split('-') for item in s.split(',')))
    

    It does 3 things:

    • split the string into "<key> - <value>" parts: s.split(',')
    • split each part into "<key> ", " <value>" pairs: item.split('-')
    • remove the whitespace from each pair: (k.strip(), v.strip())
    0 讨论(0)
  • 2020-12-08 17:24

    Here's an answer that doesn't use generator expressions and uses replace rather than strip.

    >>> s = 'A - 13, B - 14, C - 29, M - 99'
    >>> d = {}
    >>> for pair in s.replace(' ','').split(','):
    ...     k, v = pair.split('-')
    ...     d[k] = int(v)
    ...
    >>> d
    {'A': 13, 'C': 29, 'B': 14, 'M': 99}
    
    0 讨论(0)
提交回复
热议问题