Python - Dictionary

By xngo on June 14, 2019

In Python, a dictionary is similar to a list in that it contains a collection of elements. However, the main difference is that elements in a dictionary are accessed via keys and not via their position. Here is an example of a dictionary.

my_dict = { "key1": "value1", "key1": "value2" }

When to use a list or a dictionary?

Remember, a list keeps the order of elements whereas a dictionary doesn't. So, when you care about elements order, then use a list. Otherwise, use a dictonary. A dictionary associates each value with a key, whereas a list just contain values.

Examples using dictionary

ages = {}   # Create an empty dictionary.
 
ages = {'John Smith' : 99, 'Nikki Brown': 21 } # Create a dictionary with some values.
 
ages['Nikki Brown']     # Access value using key. Get the age of Nikki Brown.
 
ages['Ann Jones'] = 56  # Add to dictionary.
 
del ages['John Smith']  # Delete element.
 
len(ages)               # Size of dictionary
 
# Loop through values of a dictionary.
for v in ages.values():     # values() returns a list of values.
    print(v)
 
# Loop through keys of a dictionary.
for k in ages.keys():       # keys() returns a list of keys.
    print(k)
 
# Check existence of a key.
if 'Ann Jones' in ages.keys():
    print('Ann Jones is', ages['Ann Jones'], 'years old.')

Notes

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.