So I have this segment of code
dic = {}
for (k,v) in list:
if k in dic.keys():
dic[k] += [v]
else:
dic[k] = [v]
return dic
Is there any way I can write this in a cleaner way?
So I have this segment of code
dic = {}
for (k,v) in list:
if k in dic.keys():
dic[k] += [v]
else:
dic[k] = [v]
return dic
Is there any way I can write this in a cleaner way?
Using defaultdict
:
lst = [('a', 1), ('b', 2)]
dic = collections.defaultdict(list)
for (k, v) in lst: dic[k].append(v)
From the Examples in the docs, another way that doesn't use defaultdict
is by using setdefault
:
lst = [('a', 1), ('b', 2)]
dic = {}
for (k, v) in lst: dic.setdefault(k, []).append(v)
This method is said to be slower than the first