I.Heeren
I.Heeren

Reputation: 19

Turning a list that is already in dictionary format into a dictionary

I currently have a list

["Sun:70.00", "Zebra:80.00", "Blue:80.00", "Edwards:50.00"] 

and I'm trying to turn it into a dictionary so it looks like this

{"Sun":70.00, "Zebra":80.00, "Blue":80.00, "Edwards":50.00}

but I cant figure out how to do it.

I tried using this code

dct = {listx[i]:listx[i+1] for i in range(len(listx))}

but it combines element 0 and element 1 of the list giving me a dicitonary with only to elements.

Upvotes: 1

Views: 56

Answers (2)

kederrac
kederrac

Reputation: 17322

you could use a dictionary comprehension:

l = ["Sun:70.00", "Zebra:80.00", "Blue:80.00", "Edwards:50.00"]

d = {k: v for s in l for k, v in [s.split(':')]}
# {'Sun': '70.00', 'Zebra': '80.00', 'Blue': '80.00', 'Edwards': '50.00'}

Upvotes: 1

Mark
Mark

Reputation: 92440

You can split the strings on the ':' them and pass the tuples to the dictionary constructor. It works well as a simple generator expression passed into dict():

l =  ["Sun:70.00", "Zebra:80.00", "Blue:80.00", "Edwards:50.00"] 

d = dict(s.split(':') for s in l)
# {'Sun': '70.00', 'Zebra': '80.00', 'Blue': '80.00', 'Edwards': '50.00'}

Upvotes: 2

Related Questions