user2845399
user2845399

Reputation: 111

How to convert List in to Dictionary in python?

I have a list like this :

list1 = ["a:b","x:y","s:e","w:x"]

I want convert into dictionary like this:

dict = {'a':'b', 'x':'y','s':'e','w':'x'}

The list is dynamic. How could i achieve this ?

Upvotes: 0

Views: 133

Answers (2)

Sukrit Kalra
Sukrit Kalra

Reputation: 34493

You could do

>>> list1 = ["a:b","x:y","s:e","w:x"]
>>> dict(elem.split(':') for elem in list1)
{'a': 'b', 'x': 'y', 's': 'e', 'w': 'x'}

Upvotes: 2

Claudiordgz
Claudiordgz

Reputation: 3049

Like this?

super_dict = dict()
for el in list1:
  super_dict[el[0]] = el[-1]

Of course there could be problems if the keys are identical, you'll need to add code if needed

Upvotes: 1

Related Questions