copa america
copa america

Reputation: 23

Python: creating dictionary from a bunch of "key: value" strings?

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

Answers (2)

MRAB
MRAB

Reputation: 20654

You can write:

dict(tuple(line.split(': ')) for line in info)

Upvotes: 2

senderle
senderle

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

Related Questions