get python dictionary from string containing key value pairs

后端 未结 3 2096
我在风中等你
我在风中等你 2020-12-03 00:19

i have a python string in the format:

str = \"name: srek age :24 description: blah blah\"

is there any way to convert it to dictionary th

3条回答
  •  情深已故
    2020-12-03 00:50

    >>> r = "name: srek age :24 description: blah blah"
    >>> import re
    >>> regex = re.compile(r"\b(\w+)\s*:\s*([^:]*)(?=\s+\w+\s*:|$)")
    >>> d = dict(regex.findall(r))
    >>> d
    {'age': '24', 'name': 'srek', 'description': 'blah blah'}
    

    Explanation:

    \b           # Start at a word boundary
    (\w+)        # Match and capture a single word (1+ alnum characters)
    \s*:\s*      # Match a colon, optionally surrounded by whitespace
    ([^:]*)      # Match any number of non-colon characters
    (?=          # Make sure that we stop when the following can be matched:
     \s+\w+\s*:  #  the next dictionary key
    |            # or
     $           #  the end of the string
    )            # End of lookahead
    

提交回复
热议问题