Search code examples
pythonlistdictionaryadjacency-listadjacency-matrix

Replace values with lists in python


I've created a dictionary of employees and past companies:

{person 1: [company 2, company 3], person 2: [company 2]}

Now, I want to replace each company in each list with a list of people who have worked in that company.

I would like the final result to be an adjacency list (i.e. a dictionary with persons as both the key and values.


Solution

  • You'll need to loop through your map and create another map of company: people, then use that map to generate the third map of people: people

    pc_map = # your person: company map
    cp_map = {}
    for person, companies in pc_map.items():
        for company in companies:
            cp_map.setdefault(company, []).append(person)
    
    pp_map = {}
    for person, companies in pc_map.items():
        pp_map[person] = [cp_map[company] for company in companies]