DEV Community

Cover image for Understanding Python's Dictionary and Data Structure
Barri
Barri

Posted on

Understanding Python's Dictionary and Data Structure

Dictionaries are one of python's powerful datatype and yet they are quite underrated. Focus is placed more on Lists as they behave like arrays. Unlike lists, dictionaries are enclosed in curly braces - {} - and the values are unordered and changeable. Dictionaries make use of keys and values. The index is the key. It is unique and immutable (meaning it must either be a string, tuple or integer). The values are more flexible and can be any datatype. The key to its associated value is called a key-value pair.

The keys and It's associated value is separated by a semicolon. As an example, we'll write a dictionary that maps the value of countries and their capitals.

countries = {"USA": "Washington", "Nigeria" : "Abuja", "Croatia": "Zagreb", "Ghana" : "Capetown"}

The dictionary keys here are USA, Nigeria, Croatia, and Ghana, which happens to be the name of the countries. While Washington, Abuja, Zagreb, and Capetown are the values and are capitals of the respective countries.

Accessing data in a dictionary

To print out the entire dictionary

print(countries)

#{"USA": "Washington", "Nigeria" : "Abuja", "Croatia": "Zagreb", "Ghana" : "Capetown"}

To access particular or specific information, we use the variable name with the key inside square brackets.

countries['Nigeria']
#Abuja

This prints 'Abuja' as output, which is the capital of Nigeria is Abuja
Note that the keys are case sensitive. countries['nigeria'] will return an error while countries['Nigeria'] will return 'Abuja'.

Updating a dictionary

Let's say we made a mistake, just like we did since Capetown is not the capital of Ghana (haha, you didn't know that, did you?) and we need to update and correct this information. To change the value of Ghana,

countries['Ghana'] = 'Accra'
print(countries)

#{"USA": "Washington", "Nigeria" : "Abuja", "Croatia": "Zagreb", "Ghana" : "Accra"}

You will notice the value of Ghana has been modified to Accra.
We can also add a new country to the list by doing the same thing we did with Ghana, only this time, the key would be the name of the new country we are to add to the list.

countries['Japan'] = 'Tokyo'
print(countries)

#notice that japan has been added to the list.

Deleting a dictionary

You can remove targeted keys from a dictionary. Note that you can't delete a key without deleting its associated value. They both go together. You can also delete the entire dictionary using the del keyword.

del countries
#this will delete the entire countries dictionary. Don't use this unless you are absolutely sure you won't need the dictionary ever.
del countries['Ghana']
# will delete Ghana and it's value, Accra.

Using get()

The method get() returns a value for the given key. If the key is not available it returns None or an optional fallback or default value.

print('Capital of Nigeria is', countries.get('Nigeria'))
#Capital of Nigeria is Abuja

The output returns Abuja because Nigeria is on the dictionary collection. If we were to get the capital of a country like Zambia, the output would be

print('Capital of Zambia is', countries.get('Zambia'))
#Capital of Zambia is None

This is because Zambia is not on the list. We can also set an optional value to be returned if a key is not found.

('Capital of Zambia is', countries.get('Zambia', 'notfound'))
#Capital of Zambia is notfound

Using the 'in' keyword for dictionaries

Like lists, we can loop through dictionaries using the 'in' operator keyword.

for x in countries:
print(x)

#USA, Nigeria, Croatia and Japan

This returns only the keys of the dictionary. To return the values as well, we will use the value() function

for x in countries.values():
print(x)
or
for x in countries:
print((countries[x]))

#this returns all the values of the keys

To get the keys only, we can use the keys() function

for x in countries.keys():
print(x)

To get both keys and values mapped together, we will use the items() function

for x in countries.items():
print(x)

# ('USA', 'Washington')
('Nigeria', 'Abuja')
('Croatia', 'Zagreb')
('Japan', 'Tokyo')

Nested Dictionaries

Dictionary values can be of any data type. It can hold lists and even other dictionaries. In this part, I'll show you how nested dictionaries are accessed.

countries = {'USA' : 'Washington', 'Nigeria' : 'Abuja', 'Croatia' : 'Zagreb', 'Japan' : 'Tokyo', 'SouthAfrica' : {"Johannesburg":['Pretoria', 'Soweto', 3]}}

I added another dictionary with key as 'Johannesburg' which contains a list of 3 items. This shows the dynamicity of dictionaries. To print out Soweto from this list, 

countries['SouthAfrica']['Johannesburg'][1]
[1] is the index number of Soweto from the list.

Python dictionaries have methods and functions that I could not cover here. You can check out
https://www.programiz.com/python-programming/methods/dictionary/ to read more on it.

Oldest comments (0)