从包含键值对的字符串中获取Python字典

9

i have a python string in the format:

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

有没有办法将它转换成类似于字典的形式?
{'name': 'srek', 'age': '24', 'description': 'blah blah'}  

每个条目都是从字符串中取出的(key,value)对。我尝试通过分割字符串到列表来解决这个问题。

str.split()  

然后手动删除:,检查每个标签名称,添加到字典中。这种方法的缺点是:这种方法很麻烦,我必须手动删除每一对标签中的:,如果在字符串中有多个单词'value'(例如descriptionblah blah),每个单词都将成为列表中的一个单独条目,这是不可取的。有没有一种Pythonic的方法来获取字典(使用python 2.7)?


你...刚刚删除了之前的问题,只是为了再次提问... - Ignacio Vazquez-Abrams
是的,那个问题有错误。 - srek
1
(离题了,但是)请不要将str作为变量名。那是内置字符串类型的名称。 - Shawn Chin
3个回答

35
>>> 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'}

解释:

\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

3

没有使用 re

r = "name: srek age :24 description: blah blah cat: dog stack:overflow"
lis=r.split(':')
dic={}
try :
 for i,x in enumerate(reversed(lis)):
    i+=1
    slast=lis[-(i+1)]
    slast=slast.split()
    dic[slast[-1]]=x

    lis[-(i+1)]=" ".join(slast[:-1])
except IndexError:pass    
print(dic)

{'age': '24', 'description': 'blah blah', 'stack': 'overflow', 'name': 'srek', 'cat': 'dog'}

0

Aswini程序的另一种变体,可以按照原始顺序显示字典

import os
import shutil
mystr = "name: srek age :24 description: blah blah cat: dog stack:overflow"
mlist = mystr.split(':')
dict = {}
list1 = []
list2 = []
try:
 for i,x in enumerate(reversed(mlist)):
    i = i + 1
    slast = mlist[-(i+1)]
    cut = slast.split()
    cut2 = cut[-1]
    list1.insert(i,cut2)
    list2.insert(i,x)
    dict.update({cut2:x})
    mlist[-(i+1)] = " ".join(cut[0:-1])
except:
 pass   

rlist1 = list1[::-1]
rlist2= list2[::-1]

print zip(rlist1, rlist2)

输出

[('name', 'srek'), ('age', '24'), ('description', 'blah blah'), ('cat', 'dog'), ('stack', 'overflow')]


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接