Home > Software design >  Python dict to show values of different dict
Python dict to show values of different dict

Time:10-26

I wanted to create dictionary that will show if actors were in the same movies.

I have dict of actors:

actors = {'1': 'John', '2': 'Richard', '3': 'Lisa', '4': 'Jennifer'}

and list of actors (keys from dictionary actors) that were in the same movie

was_in_movie = [(1,2), (1,3), (3,4)]

I am creating new dict using defaultdict

new_dict = defaultdict(set)

for element1, element2 in was_in_movie:
    for a, b in was_in_movie:
        new_dict[a].add(b)
        new_dict[b].add(a)

print(dict(new_dict))

And this is my output:

{1: {2, 3}, 2: {1}, 3: {1, 4}, 4: {3}}

Actor 1 been in movie with actor 2 and 3 etc. I got what I wanted, but now im struggling to change keys from dict actors to values, so the output will be:

{'John': {'Lisa', 'Richard'}, 'Richard': {'John'}, 'Lisa': {'John', 'Jennifer'}, 'Jennifer': {'Lisa'}}

How to achive it using list was_in_movie ?

CodePudding user response:

You can do with mapping function here,

def mapping(k):
    actors.get(str(k))

new_dict = defaultdict(set)
for element1, element2 in was_in_movie:
    for a, b in was_in_movie:
        new_dict[mapping(a)].add(mapping(b))
        new_dict[mapping(b)].add(mapping(a))

Result,

defaultdict(<class 'set'>, {'John': {'Richard', 'Lisa'}, 'Richard': {'John'}, 'Lisa': {'John', 'Jennifer'}, 'Jennifer': {'Lisa'}})
  • Related