Skip to content

Instantly share code, notes, and snippets.

@IndhumathyChelliah
Created July 15, 2020 22:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IndhumathyChelliah/f9f41b05477085aad584ca22a3a890e6 to your computer and use it in GitHub Desktop.
Save IndhumathyChelliah/f9f41b05477085aad584ca22a3a890e6 to your computer and use it in GitHub Desktop.
from collections import defaultdict
l=[('red',1),('green',2),('blue',3),('red',4)]
d=defaultdict(list)
#default factory argument is list.
for k,v in l:
d[k].append(v)
print (d)#Output:defaultdict(<class 'list'>, {'red': [1, 4], 'green': [2], 'blue': [3]})
#In normal dictionary
d1=dict()
for k,v in l:
if k not in d1:
d1[k]=[v]
else:
d1[k].append(v)
print (d1)
#Output:{'red': [1, 4], 'green': [2], 'blue': [3]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment