Kevin Klarić Kevin Klarić - 3 months ago 20
Python Question

List of tuple pairs into dictionary

I am having trouble with dictionaries in Python. I realise the task is very simple, yet I can't figure it out. My task is to write a function, which converts a list of tuples into a dictionary, where the keys of the dictionary represent the people (from the tuples) and the values represent their friends. Per exp:

pairs_of_people = {("Adam", "Brian"), ("Adam", "Gabe"), ("Adam", "Hagan"),
("Brian", "Calvin"), ("Brian", "Hagan"),
("Calvin", "Dan")}`

must return:

{"Adam": {"Brian", "Gabe", "Hagan"}, "Brian": {"Adam", "Hagan", "Calvin"}, "Calvin": {"Brian", "Dan"}}

Any help? Thank you. An if someone has a good intro on dictionaries somewhere, it would be greatly appreciated. I just can't figure them out.


A very quick way to brute force this solution is to use a defaultdict. This will add to our output dictionary the people and their friends if either the "person" or the "friend" is a required key (the first person in the input tuples).

from collections import defaultdict

pairs_of_people = {("Adam", "Brian"), ("Adam", "Gabe"), ("Adam", "Hagan"),
               ("Brian", "Calvin"), ("Brian", "Hagan"),
               ("Calvin", "Dan")}

required_keys = {t[0] for t in pairs_of_people}

out = defaultdict(set)

for person, friend in pairs_of_people:
    if person in required_keys:
    if friend in required_keys:

>> {"Adam": {"Brian", "Gabe", "Hagan"}, "Brian": {"Adam", "Hagan", "Calvin"},
    "Calvin": {"Brian", "Dan"}}