Keys with multiple values

I’ve tried to make a dictionary where keys hold multiple values.

regions = ['Region Hovedestaden', 'Region Midtjylland', 'Region Nordjylland', 'Region Sjælland', 'Region Syddanmark']

communes = {
regions[0]: ('Albertslund', 'Brøndby'),
regions[1]: ('Horsens', 'Ikast-Brande'),
regions[2]: ('Hjørring', 'Jammerbugt'),
regions[3]: ('Guldborgsund', 'Holbæk'),
regions[4]: ('Ærø', 'Aabenraa')
}
print(communes)
print(communes[regions[2]])

#This is where it goes wrong
city = communes.get(regions[2][1], 'Something is wrong')
print(city)

However I can’t get the 2nd value from my regions[2].
The .get say’s ‘Something is wrong’.
I have the feeling regions[2][1] is the problem.
I tried to search the internet, but can’t figure out what I’m doing wrong.

If i put a

print(communes[regions[2][1]])

at the end the shell gives me the following error:
Traceback (most recent call last):
File “ex39_drill.py”, line 37, in
print(communes[regions[2][1]])
KeyError: ‘e’

Hello @ktrager

I found the problem.
It was the closing bracket that was at wrong place. This:

city = communes.get(regions[2])[1]
print(city)

Gave me the output: ”Jammerbugt”

The get function gives the value connected to the key you provide inside the brackets.
Since you have a tupel as value you can choose which item from the tupel with another [] directly after the get function.
If not provided you will get all items in the tupel.

2 Likes

You might want to consider using lists rather than tuples if you ever expect your regions to change contents. If not, all is good!

1 Like

Thank you @ulfen69
I think i misunderstood that the get only connects to the key.

Thanks for clarifying.

I think regions[2][1] will get “Region Midtjylland”, and then get the 1st character of that string. Try it in the python shell.

1 Like