Is it possible to statically define a dictionary which contains another dictionary without using another variable?

Question

In this exercise, one of the values in the library dictionary is set from the plays dictionary. Is it possible to statically define a dictionary which contains another dictionary as a value?

Answer

Yes, when you define the dictionary you simply define another dictionary inside the {} brackets. The following code example shows a population dictionary which contains dictionaries for each state that contains cities and population numbers.

population = {"California": {"Los Angeles": 3971883,
                             "San Diego": 1394928,
                             "San Jose": 1026908},
              "Texas": {"Houston": 2296224,
                        "San Antonio": 1469845}
              }
10 Likes

looping through this to pull out information i am sure is possible but seems daunting. Better to keep it simple and create several dictionaries?

2 Likes

Nested data structures are common. You should rise to the occasion (challenge? No idea, my english isn’t that good)

3 Likes

My melting brain is screaming “thiiiis wiiiilll beeee fuuuuun”

11 Likes

:rofl: I’m glad I’m not the only one who’s brain is getting fried.

Here’s a simple way to extract nested values:

print(library["The Best Songs"]["Imagine"])
// Prints out 44

Much like retrieving data from nested lists/arrays, of course.

1 Like

For this question asked by @ajaxninja66418 , If I want to update the values “California”, how would I go about it?Eg. I want to add more cities in California with their relative population count… how would the code be written?

I would say the same way you add something to a dictionary:

my_dict['new_key"] = "new value"

but you will first need to look-up California in the population dictionary.

population['California'].update({'San Francisco': 873965, 'Fresno': 542107})

We can do it by this piece of code.`

3 Likes