-
-
Save IndhumathyChelliah/f9f41b05477085aad584ca22a3a890e6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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