Dictionaries

Dictionary length, keyword in, and nested dictionaries

Learn how to use the `len` function and `in` keyword with dictionaries. Also, discover how to organize complex hierarchical data structures using nested dictionaries.


Let's create a new dictionary with some English-Portuguese translations:

Python

We can use the English word as a key to find its translation:

Python
Output

Just like with strings, tuples, and lists, you can apply len() function to dictionaries.

len() will return the number of key-value pairs:

Python
Output

To check if a dictionary contains a specific key, use the in keyword.

Let's check if we have a translation for 'hi' and add it if necessary:

Python
Output

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python

Sometimes you need to store more complex hierarchical data structures that cannot be represented by a single dictionary.

That's when we create dictionaries that contain other, nested dictionaries as their values.

Here's an example of such nested dictionaries:

Python

To access a value within the inner dictionary, we need to use multiple keys:

Python
Output

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python