Converting List Of Tuples In Python To Dictionary
Imagine a social network website which allows people to specify which other people they like. We can store information about who likes who in a list of tuples, such as the one assi
Solution 1:
Use either defaultdict(list)
or dict.setdefault(..., [])
- there's not much difference in performance or readability, so it's really a matter of taste. I prefer using setdefault
:
likes = {}
for k, v in friendface:
likes.setdefault(k, []).append(v)
Solution 2:
Here is a solution using defaultdict
:
def likes_relation(friendface):
d =defaultdict(list)
for k, v in friendface:
d[k].append(v)
return d
Result:
>>> fork,vinlikes_relation(f).items():
print (k, v)
Hera['Aphrodite']Apollo['Aphrodite']Aphrodite['Apollo', 'Zeus', 'Athena']Zeus['Apollo', 'Aphrodite', 'Athena', 'Hera']Athena['Hera', 'Aphrodite']
Hope this helps!
Post a Comment for "Converting List Of Tuples In Python To Dictionary"