Creating a dictionary from a string

前端 未结 7 1969
轻奢々
轻奢々 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: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}
    

提交回复
热议问题