user2127168 user2127168 - 1 month ago 7
Python Question

Python 3: convert a list into a dictionary

I am looking for a simple method to convert a list into a dictionary. I have a simple list:

leet =['a','4','b','l3','c','(','d','[)','e','3','g','6','l','1','o','0','s','5','t','7','w','\/\/']


which I want to easily convert to a dictionary. I have tried using defaultdict but I don't quite understand what it is doing ( I found this code in a previous answer):

>>> from collections import defaultdict
>>> dic = defaultdict(list)
>>> for item in leet:
key ="/".join(item[:-1])
dic[key].append(item[-1])


>>> dic
defaultdict(<class 'list'>, {'\\:/:\\': [], '': ['a', '4', 'b', 'c', '(', 'd', 'e', '3', 'g', '6', 'l', '1', 'o', '0', 's', '5', 't', '7', 'w'], 'l': ['3'], '[': [')'], '\\///\\': ['/']})


Ultimately, I want to read in the data from a txt file ( line by line) into a list and convert to a dictionary for the rest of the simple program.
I'm looking for a straight-forward way to achieve this.

Thanks

Answer Source

Not sure you're going down the right path with a defaultdict, convert to a dict by grouping into pairs, then use dict.get to cater for when there isn't a matching key:

leet =['a','4','b','l3','c','(','d','[)','e','3','g','6','l','1','o','0','s','5','t','7','w','\/\/']

lookup = dict(zip(*[iter(leet)] * 2))
text = 'how are you?'
blah = ''.join(lookup.get(ch, ch) for ch in text)
# h0\/\/ 4r3 y0u?