Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 593
copa america Avatar asked Feb 25 '26 05:02

copa america


1 Answers

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)}
like image 140
senderle Avatar answered Feb 27 '26 18:02

senderle