Kevin Klarić Kevin Klarić - 17 days ago 4
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.

Answer

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:
        out[person].add(friend)
    if friend in required_keys:
        out[friend].add(person)

print(out)
>> {"Adam": {"Brian", "Gabe", "Hagan"}, "Brian": {"Adam", "Hagan", "Calvin"},
    "Calvin": {"Brian", "Dan"}}