pythonhelp2210
pythonhelp2210

Reputation: 47

Using immutable datatypes for the keys in a dictionary

Hello I cannot seem to get my code to return any value.

My original code was:

 room_numbers = {
    ['Freddie', 'Jen']: 403,
    ['Ned', 'Keith']: 391,
    ['Kristin', 'Jazzmyne']: 411,
    ['Eugene', 'Zach']: 395
    }

My new code is listed below

room_numbers = {
tuple (['Freddie', 'Jen']): (403),
tuple (['Ned', 'Keith']): 391,
tuple (['Kristin', 'Jazzmyne']): 411,
tuple (['Eugene', 'Zach']): 395
}

I changed it so I can use the correct data type. I understood that you can not use mutable data types for dictionaries and Python requires us to use immutable datatypes for the keys in a dictionary. However, I cannot figure out how to call upon the dictionary. However, how when I try to call upon the different data type I can not print out any results.

Can you please answer if my change in the code above is correct and how come I can not do the following:

print (room_numbers['Freddie'])  #why does this not return 403?

I want to call upon the unique keys to return the unique values assigned to them. What is the process python code for this?

Upvotes: 0

Views: 95

Answers (2)

Jean-François Fabre
Jean-François Fabre

Reputation: 140188

If you have this dictionary with tuple items as keys:

room_numbers = {
     ('Freddie', 'Jen'): 403,
     ('Ned', 'Keith'): 391,
     ('Kristin', 'Jazzmyne'): 411,
     ('Eugene', 'Zach'): 395
     }

you want to transform this dictionary by creating one key per name with the same value for all names of one same tuple. Achieve it with a dictionary comprehension:

flat_dict = {k:v for kt,v in room_numbers.items() for k in kt}

result:

>>> flat_dict
{'Freddie': 403, 'Jen': 403, 'Ned': 391, 'Keith': 391, 'Kristin': 411, 'Jazzmyne': 411, 'Eugene': 395, 'Zach': 395}

now accessing a name gives you the value.

Upvotes: 0

TrebledJ
TrebledJ

Reputation: 8997

Nothing is returned for room_numbers['Freddie'], in fact an error should be raised, since there is no key Freddie in the dictionary room_numbers. However, you can access the ('Freddie', 'Jen') key, since that exists.

room_numbers[('Freddie', 'Jen')]  # or room_numbers['Freddie', 'Jen']

But this is probably not what you're looking for. You're probably after

room_numbers = {
    'Freddie': 403,
    'Jen': 403,
    'Ned': 391,
    'Keith': 391,
    ...
}

This allows you to do room_numbers['Freddie'] since there is a Freddie key in this particular dictionary.

Upvotes: 1

Related Questions