Reputation:
I have a list
['E:3', 'B:13', 'G:6', 'F:|=', 'H:}{', 'I:!', 'B:|3', 'K:|{', '']
and I would like to convert it into a dictionary {'E':'3', 'B':'13', 'G':'6', 'F':'|=', 'H':'}{', 'I':'!', 'B':'|3', 'K':'|{'}
How would I be able to do this?
Upvotes: 1
Views: 85
Reputation: 845
You can do this through a dict comprehension. This will loop through the list, splitting each item into two parts using the first for the dict key and the second for the value.
example_dict = {x.split(":")[0]: x.split(":")[1] for x in example_list if x}
Upvotes: 2
Reputation: 49318
Simply split it on :
and send it to dict()
, filtering out the empty string:
>>> l = ['E:3', 'B:13', 'G:6', 'F:|=', 'H:}{', 'I:!', 'B:|3', 'K:|{', '']
>>> result = dict(item.split(':') for item in l if item)
>>> result
{'I': '!', 'H': '}{', 'K': '|{', 'E': '3', 'G': '6', 'B': '|3', 'F': '|='}
Also note that, as Psidom says in a comment, dictionaries cannot contain duplicate keys, so only the most recent duplicate will end up in the result.
Upvotes: 8