0

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?

1
  • What should happen if there are two people with the same first name (but different last names)? Commented May 25, 2019 at 19:53

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.