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



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

suppose have loaded list:

info = ['apple: 1', 'orange: 2', 'grape: 3']

how can turn like

info = {line[0]: line[1] line.split(': ') in info}

so have dict?

you're close!

>>> info = ['apple: 1', 'orange: 2', 'grape: 3'] >>> info = dict(line.split(': ') line in info) >>> info {'orange': '2', 'grape': '3', 'apple': '1'}

you way tried in python 2.7+, you'd have split lines separately, using dict better.

here's mean:

info = ['apple: 1', 'orange: 2', 'grape: 3'] info = {fruit:num fruit, num in (line.split(': ') line in info)}

python list dictionary

Comments

Popular posts from this blog

iphone - Dismissing a UIAlertView -

c# - Can ProtoBuf-Net deserialize to a flat class? -

javascript - Change element in each JQuery tab to dynamically generated colors -