Day 26: Dictionariception

What is Dictionariception meant?
Dictionaries can contain key-value pairs where the values are again dictionaries. Familiar? Yes, same like Lists.

How does it look like?

# Dictionary of dictionaries
europe = { 'spain': { 'capital':'madrid', 'population':46.77 },
           'france': { 'capital':'paris', 'population':66.03 },
           'germany': { 'capital':'berlin', 'population':80.62 },
           'norway': { 'capital':'oslo', 'population':5.084 } }

How to access the value of a capital?

# Print out the capital of France

# Output:

Next, create a new dictionary calls data with key ‘capital’, ‘population’, add this dictionary into the above dictionary, europe and print out the europe. How does the codes looks like?

# Create sub-dictionary data
data = {'capital':'rome', 'population':59.83}

# Add data to europe under key 'italy'
europe['italy'] = data

# Print europe

# Output:
{'italy': {'capital': 'rome', 'population': 59.83}, 'norway': {'capital': 'oslo', 'population': 5.084}, 'germany': {'capital': 'berlin', 'population': 80.62}, 'france': {'capital': 'paris', 'population': 66.03}, 'spain': {'capital': 'madrid', 'population': 46.77}}

Dictionaries are unordered mapping objects, so the ‘italy’ may appear unordered in our output above.

Summary of the day:

  • Dictionaries with sub-dictionaries.
  • How to add and access a sub-dictionary.

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s