Reputation: 171
I am trying 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?
Upvotes: 1
Views: 542
Reputation: 113915
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
Upvotes: 0
Reputation: 2130
>>> s = "Milk, Cheese, Bottle"
>>> d = dict.fromkeys(s.split(', '),"NULL")
>>> d
{'Cheese': 'NULL', 'Milk': 'NULL', 'Bottle': 'NULL'}
Upvotes: 5
Reputation: 573
>>> from collections import defaultdict:
>>> s = "Milk, Cheese, Bottle"
>>> j = s.split(',')
>>> d = defaultdict()
>>> for k in j:
d[k]= 'NULL'
>>> dict(d)
Upvotes: 0
Reputation: 90999
dict.fromkeys((k.strip() for k in "Milk, Cheese, Bottle".split(',')), 'NULL')
Upvotes: 2
Reputation: 361585
>>> string = 'Milk, Cheese, Bottle'
>>> dict((key, None) for key in string.split(', '))
{'Cheese': None, 'Milk': None, 'Bottle': None}
Upvotes: 8
Reputation: 22659
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(', ')}
Upvotes: 1