Reputation: 23
Suppose I have loaded this into a list:
info = ['apple: 1', 'orange: 2', 'grape: 3']
How can I turn that into something like
info = {line[0]: line[1] for line.split(': ') in info}
So that I actually have a dict?
Upvotes: 2
Views: 450
Reputation: 150977
You're very close!
>>> info = ['apple: 1', 'orange: 2', 'grape: 3']
>>> info = dict(line.split(': ') for line in info)
>>> info
{'orange': '2', 'grape': '3', 'apple': '1'}
You could do it the way you tried to in Python 2.7+, but you'd have to split the lines separately, so using dict
is better.
Here's what I mean:
info = ['apple: 1', 'orange: 2', 'grape: 3']
info = {fruit:num for fruit, num in (line.split(': ') for line in info)}
Upvotes: 7