String to dictionary
I am try开发者_StackOverflow中文版ing to convert a string to dictionary. Example:
Milk, Cheese, Bottle
The program will convert it to dictionary.
{"Milk":"NULL", "Cheese":"NULL", "Bottle":"NULL"}
How do I do it?
>>> string = 'Milk, Cheese, Bottle'
>>> dict((key, None) for key in string.split(', '))
{'Cheese': None, 'Milk': None, 'Bottle': None}
>>> s = "Milk, Cheese, Bottle"
>>> d = dict.fromkeys(s.split(', '),"NULL")
>>> d
{'Cheese': 'NULL', 'Milk': 'NULL', 'Bottle': 'NULL'}
dict.fromkeys((k.strip() for k in "Milk, Cheese, Bottle".split(',')), 'NULL')
s = 'Milk, Cheese'
d = { }
for s in s.split(', '):
d[s] = 'NULL'
You can also use dictionary comprehensions in the latest Python versions:
s = 'Milk, Cheese'
d = {key:'NULL' for key in s.split(', ')}
>>> from collections import defaultdict:
>>> s = "Milk, Cheese, Bottle"
>>> j = s.split(',')
>>> d = defaultdict()
>>> for k in j:
d[k]= 'NULL'
>>> dict(d)
This is essentially the same solution as Zaur Nasibov's, but using list comprehension to run the for loop in fewer lines
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}
Hope this helps
精彩评论