Python 字符串到字典

Python 字符串到字典,python,Python,我正在尝试将字符串转换为字典。例如: Milk, Cheese, Bottle 程序将把它转换成字典 {"Milk":"NULL", "Cheese":"NULL", "Bottle":"NULL"} 我该怎么做 s = 'Milk, Cheese' d = { } for s in s.split(', '): d[s] = 'NULL' 您还可以在最新的Python版本中使用字典理解: s = 'Milk, Cheese' d = {key:'NULL' for key in

我正在尝试将字符串转换为字典。例如:

Milk, Cheese, Bottle
程序将把它转换成字典

{"Milk":"NULL", "Cheese":"NULL", "Bottle":"NULL"}
我该怎么做

s = 'Milk, Cheese'
d = { }
for s in s.split(', '):
    d[s] = 'NULL'
您还可以在最新的Python版本中使用字典理解:

s = 'Milk, Cheese'
d =  {key:'NULL' for key in s.split(', ')}
您还可以在最新的Python版本中使用字典理解:

s = 'Milk, Cheese'
d =  {key:'NULL' for key in s.split(', ')}

这本质上与Zaur Nasibov的解决方案相同,但使用列表理解以更少的行运行for循环

s = "Milk, Cheese, Bottle"
d = dict((i, None) for i in [i.strip() for i in s.split(',')])

>>> print d
{'Cheese': None, 'Milk': None, 'Bottle': None}

希望这对您有所帮助

这与Zaur Nasibov的解决方案基本相同,但使用列表理解以更少的行运行for循环

s = "Milk, Cheese, Bottle"
d = dict((i, None) for i in [i.strip() for i in s.split(',')])

>>> print d
{'Cheese': None, 'Milk': None, 'Bottle': None}
希望这有帮助

 >>> from collections import defaultdict:
 >>> s = "Milk, Cheese, Bottle"
 >>> j = s.split(',')
 >>> d = defaultdict()
 >>> for k in j:
     d[k]= 'NULL'
 >>> dict(d)
s = "Milk, Cheese, Bottle"
d = dict((i, None) for i in [i.strip() for i in s.split(',')])

>>> print d
{'Cheese': None, 'Milk': None, 'Bottle': None}