Search code examples
pythondictionarydefaultdict

Use Keys, values in one dict to get values in another dict in python


I have the following dictionary

names= 'bob julian tim martin rod sara joyce nick beverly kevin'.split() ids = range(len(names)) users = dict(zip(ids, names))

so the results is

{0: 'bob', 1: 'julian', 2: 'tim', 3: 'martin', 4: 'rod', 5: 'sara', 6: 'joyce', 7: 'nick', 8: 'beverly', 9: 'kevin'}

I have another default dict called new_dict with the following

{5: [6, 7, 9]}

Ultimately I am trying to use keys and values from new_dict to pull the values from the users dict to place it in a final_dict that looks like this

{sara: [joyce, nick, kevin]}

The issue is it is saying that the dict is unhashable so code like this does not work. How can you use keys, value in one dict to get the values in another one?

users[new_dict.keys()]

but when you do this users[5] this will return sara like I want


Solution

  • First, there's a simpler way to define users:

    users = dict(enumerate(names))
    

    Your desired dict can be defined with

    {users[name]: [users[friend] for friend in friends] for name, friends in new_dict.items()}
    

    First, you iterate over the key/values pairs in new_dict. Both the key and its associated values are used as keys in user.

    There's a slightly shorter way to write this, using operator.itemgetter.

    from operator import itemgetter
    
    {users[k]: list(itemgetter(*v)(users)) for k, v in new_dict.items()}
    

    itemgetter creates a function which performs a look up on its argument using each of the arguments to itemgetter as keys, returning the results as a tuple.