Compound Data Structure
In the last article, we talked about dictionaries and how they are composed of key-value pairs. However for a very simple key, we assigned a very simple value. What if I wanted to store more information about my groceries. What if instead of just storing price, I wanted to also store the country of origin. Let's explore how we can do this with compound data structures.
Recall the example from the previous article:
grocery_items = {'bananas': 1.29, 'apples': 2.99, 'papayas': 1.39
In order to add more information to each key in our dictionary, we can nest dictionaries within dictionaries.
grocery_items = { 'bananas': {'price': 1.29, 'country of origin': 'Guatemala'}, 'apples': {'price': 2.99, 'country of origin': 'United Kingdom'}, 'papayas': {'price': 1.39, 'country of origin': 'Costa Rica'} }
In this compound data structure, we have grocery_item keys like bananas
, apples
and papayas
, and each of these keys has a dictionary composed of price
and country of origin
.
How to index a Compound Data Structure
Accessing compound data structures is similar to dictionaries (they are dictionaries at their core):
print(grocery_items['bananas'])
>> {'price': 1.29, 'country of origin': 'Guatemala'}
Now what if I just wanted to access the country of origin
of the product?
You can also grab it based on it's key:
print(grocery_items['bananas']['country of origin'])
>> Guatemala
You just have to add an extra set of brackets to access a nested key. First we looked up the key bananas
, then we went deeper and looked up country of origin
which returned the value Guatemala