Python Dictionaries
Python Dictionaries

Python dictionaries is a popular data type or data structure used for various purposes. They are unordered collections of key-value pairs. They are mutable, which means you can change their elements after they have been created!.

Developers use Dictionaries widely for solving several tasks including: involving mapping, lookup tables, and storing data in key-value pairs.

Characteristics of Python Dictionary Items

These are the some of the Characteristics of Python Dictionaries you should consider when you want to understand deeply.

  • They store key-value pairs. This means that each element in a dictionary consists of two parts: key and value. See example of this below.
  • Dictionaries are mutable. This means, you can able to change their elements after you have been created one.
  • Dictionaries are unordered. This means, elements in the dictionary do not have a defined order.
  • Dictionary keys must be unique. In dictionary, you cannot have two similar key values or duplicated keys.

Simple Example of Python Dictionary

In the following dictionary, we want to use simple dictionary data type and use the following keys "name", "age", and "city" and the following values"John", 30, and "New York".

Example:


# Create a Python Dictionary
my_dict = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

# Print the values in the Python Dictionary
print(my_dict)  

Output:


{'name': 'John', 'age': 30, 'city': 'New York'}

Data Types in Dictionaries

In Python Dictionaries you can store elements of different data types. For example, you can store name as string and salary values as int or float, tuples, sets and many more.

In the following example, I will show you how such examples work as we store several data with different data types in Python dictionaries.

Example:


#IN DICTIONARY VARIABLE YOU CAN STORE ANY DATAT TYPES SUCH AS INT, STRING, BOLLEAN, LIST DATA ETC
var_dictionaries = {
                        "name": "John Kurdish",
                        "race": "British",
                        "weight": 78.80,
                        "student": True,
                        "age": 38,
                        "foodlist": ["Rice","Fish","Burger","Fried eggs"],
                        "carlist": {"Toyoto","Mercedes","BMW","Honda","Volvo"}
                   }

print("")
print(var_dictionaries)

Output:


{'name': 'John Kurdish', 'race': 'British', 'weight': 78.8, 'student': True, 'age': 38, 'foodlist': ['Rice', 'Fish', 'Burger', 'Fried eggs'], 'carlist': {'Toyoto', 'Volvo', 'Honda', 'Mercedes', 'BMW'}}

In the above dictionary, we have used different data types such as:

  1. Strings: Used for keys like 'name', 'race', and values like 'John Kurdish', 'British'.
  2. Float: Used for the 'weight' key, with a value of 78.80.
  3. Boolean: Used for the 'student' key, with a value of True.
  4. Integer: Used for the 'age' key, with a value of 38.
  5. List: Used for the 'foodlist' key, containing a list ["Rice", "Fish", "Burger", "Fried eggs"].
  6. Set: Used for the 'carlist' key, containing a set {"Toyoto", "Mercedes", "BMW", "Honda", "Volvo"}.

Create Python Dictionary Using dict() Constructor

There are another way of creating or declaring a Python Dictionary using Dictionary constructor. In this case we create a dictionary using the dict() constructor in Python.

Example:


# Creating a dictionary using the dict() constructor
my_dict = dict(
    name="John Kurdish", 
    race="British", 
    weight=78.80, 
    student=True, 
    age=38
    )

print(my_dict)

Output:


{'name': 'John Kurdish', 'race': 'British', 'weight': 78.8, 'student': True, 'age': 38}

Dictionary Constructor (dict()) uses slightly different syntax compared to the previous ways of declaring dictionary data. I give the following key difference.

  • The dict() constructor allows you to create dictionaries using keyword arguments, where the keys are specified as arguments without quotes.
  • It provides a convenient way to create dictionaries when you have key-value pairs available as separate variables.
  • Keys must be valid Python identifiers (variable names).

While the previous method ‘Normal Dictionary Declaration‘, the keys are enclosed in quotes e.g. (‘name’) and separated from their corresponding values using colons (:) while the constructor procedure uses (=).

Checking Data Type in Dictionaries

In this example i will show you how you can view if the variable is dictionary or not. In this case we use one common method called type()which returns the data type of the variable passed inside.

Example:


my_dict = dict(
    name="John Kurdish", 
    race="British", 
    weight=78.80, 
    student=True, 
    age=38
    )

# Check dictionaries type
print(type(my_dict))

Output:


<class 'dict'>

Checking the length of the Dictionaries

In Python you can check the size of the dictionary using the len() method.

Example:


# Check dictionaries length
my_dict = dict(
    name="John Kurdish", 
    race="British", 
    weight=78.80, 
    student=True, 
    age=38
    )

# Check dictionaries length
print(len(my_dict))

Output:


5

In the above example themy_dict contains 5 key-value pairs: name: "John Kurdish", race: "British", weight: 78.80, student: True, age: 38. Therefore, the length of my_dict is 5,

Access Dictionary Items

In Python Dictionary, we can access dictionary items using their keys. In this example I show you how it has been done correctly.

Example:


# Access Dictionary Items
my_dict = dict(
    name="John Kurdish", 
    race="British", 
    weight=78.80, 
    student=True, 
    age=38
    )

# Access items using keys
print(my_dict['name'])
print(my_dict['race'])
print(my_dict['weight'])
print(my_dict['student'])
print(my_dict['age'])

# Another example
# Create a Python Dictionary
my_dict = {
    "name": "John",
    "age": 30,
    "city": "New York"
}
print()
# Print the values in the Python Dictionary
print(my_dict["name"])  
print(my_dict["age"])  
print(my_dict["city"])  

Output:


John Kurdish
British
78.8
True
38

John
30
New York

Changing Dictionary Items in Python

As I said earlier, the Python Dictionaries are mutable, which means that you can change the elements stored in it even after they have been created.

Example:


# Change Dictionary Items
my_dict = dict(
    name="John Kurdish", 
    race="British", 
    weight=78.80, 
    student=True, 
    age=38
    )
# before changed 
print(my_dict)

# Change items using keys
my_dict['age'] = 35
my_dict['weight'] = 95

print(my_dict)

Output:


{'name': 'John Kurdish', 'race': 'British', 'weight': 78.8, 'student': True, 'age': 38}
{'name': 'John Kurdish', 'race': 'British', 'weight': 95, 'student': True, 'age': 35}

Adding Dictionary Items in Python

If you want to add a new item in an already created dictionary is possible in Python. Therefore, there are various methods like assignment and the update() method. Let me show you both procedures.

Example:


my_dict = dict(
    name="John Kurdish", 
    weight=78.80, 
    age=38
    )

# before updated or added new item in dictionary
print(my_dict)

# Add items using assignment
my_dict['student'] = False

# Add items using the update() method
my_dict.update({'race': 'Canadian'})

print(my_dict)

Output:


{'name': 'John Kurdish', 'weight': 78.8, 'age': 38}
{'name': 'John Kurdish', 'weight': 78.8, 'age': 38, 'student': False, 'race': 'Canadian'}

Remove Dictionary Items in Python

Dictionary in Python is mutable, so we can remove things we specified before. So if you want to remove an existing items from a dictionary we suggest you to use methods like pop(), popitem(), and del. These methods behave differently closely see he example below.

Example:


# Remove Dictionary Items
my_dict = dict(
    name="John Kurdish", 
    race="British", 
    weight=78.80, 
    student=True, 
    age=38,
    city= 'New York'
    )

# Remove items using pop()
my_dict.pop('age')
print(my_dict)

# Remove the last item using popitem()
my_dict.popitem()
print(my_dict)

# Remove items using del
del my_dict['student']

print(my_dict)

Output:


{'name': 'John Kurdish', 'race': 'British', 'weight': 78.8, 'student': True, 'city': 'New York'}
{'name': 'John Kurdish', 'race': 'British', 'weight': 78.8, 'student': True}
{'name': 'John Kurdish', 'race': 'British', 'weight': 78.8}

Let me explain to you the above methods used and how they work. As you know Python support these methods to alter (remove or delete) the data. in this case the dictionary data. These methods are pop(), popitem(), and del and they are intended to remove elements from dictionaries.

These different behaviors:

1. pop(key):

  • What it does: The pop() method is used to remove the item with the specified key from the dictionary and returns its value.
  • Syntax: dictionary.pop(key)
  • Example: my_dict.pop('age')
  • It is must to provide a default value and If the key is not found, it raises a KeyError

2. popitem():

  • What it does: This popitem() method removes and returns the last key-value pair (item) inserted into the dictionary.
  • Not compulsory to provide argument. In another words, this method doesn’t accept any arguments.
  • Syntax: dictionary.popitem()
  • Example: my_dict.popitem()
  • Only raises a KeyError if the dictionary provided is empty.

3. del:

  • What it does: The del statement removes a specified key or keys along with their values from the dictionary. It can also be used to delete the entire dictionary or clear its contents.
  • Syntax: del dictionary[key] or del dictionary
  • Example: del my_dict['student'] or del my_dict

Note: Be careful using these methods in real data especially the del method as they delete data permanently

Loop Through Dictionary Items in Python

Yes, it is possible and simple to iterate what is inside the dictionary. In Python, allows us to iterate over dictionary items using a for loop or even other loops that I will show you later on.

This example shows how to:

  • Print all the keys in the dictionary only using the with keys() method and without it.
  • Print or display all the values in the dictionary without keys using through indexing and with values() method.
  • Print or display both keys and values using indexing procedure and item() method.

Example:



# Loop Through Dictionary Items
my_dict = dict(
    name="John Kurdish", 
    race="British", 
    weight=78.80, 
    student=True, 
    age=38,
    city= 'New York'
    )

# loop only the keys
for key in my_dict:
    print(key)

print()
# alternative way of printing keys
for key in my_dict.keys():
    print(key)

print()

#-------------------------------------
# loop only the values
for key in my_dict:
    print(my_dict[key])

print()
# alternative way of printing values
for value in my_dict.values():
    print(value)

print()

#-----------------------
# Loop through both the dictionary keys and values
for key in my_dict:
    print(key, ':', my_dict[key])

print()

# Loop through both the dictionary keys and values
for key, value in my_dict.items():
    print(key, ':', value)

Output:


name
race
weight
student
age
city

name
race
weight
student
age
city

John Kurdish
British
78.8
True
38
New York

John Kurdish
British
78.8
True
38
New York

name : John Kurdish
race : British
weight : 78.8
student : True
age : 38
city : New York

name : John Kurdish
race : British
weight : 78.8
student : True
age : 38
city : New York

Additional examples to practice are also provided as follows:

Example:


var_dict={
    "name": "Leyla Ali",
    "age": 45,
    "city": "London",
    "color": "Blck",
    "origin": "Nigeria",
    "religion": "Islam",
    "colors":{"red","yellow","marron","green"}
}

#EXAMPLE 1: PRINT ALL KEY NAMES OF A PYTHON DICTIONARY USING FOR LOOP
#USING KEYS() METHOD
print("")
print("Key names using keys() method are:")
for i in var_dict.keys():
    print(i)

#USING ITEMS() METHOD
print("")
print("Key names using items() method are:")
for i in var_dict.items():
    print(i)

#ALTERNATIVE OF THE ABOVE WITHOUT USING ANY METHOD
print()
print("Key names without using any method are:")
for i in var_dict:
    print(i)


#EXAMPLE 2: PRINT ALL VALUES OF A PYTHON DICTIONARY USING FOR LOOP
print("")
print("Value items using values() method are:")
for i in var_dict.values():
    print(i)


#YOU CAN ALSO PRINT ALL THE VALUES IN THE DICTIONARY USING INDEXING
print("")
print("Value items using indexing technique")
for i in var_dict:
    print(var_dict[i])

#YOU CAN ALSO PRINT ALL THE VALUES IN THE DICTIONARY USING KEYS() METHOD
print("")
print("Value items using keys method and ndexing technique")
for i in var_dict.keys():
    print(var_dict[i])

#EXAMPLE 3. PRINT ALL KEYS AND VALUES IN THE DICTIONARY USING FOR LOOP
#YOU CAN ALSO PRINT ALL THE KEY NAMES AND VALUES IN THE DICTIONARY USING ITEMS() METHOD
print("")
print("Value items using items method and ndexing technique")
for i in var_dict.items():
    print(i)

#ALTERNATIVELY, YOU CAN ALSO PRINT ALL THE KEY NAMES AND VALUES IN THE DICTIONARY USING ITEMS() METHOD
print("")
print("Value items using items method and ndexing technique")
for i,j in var_dict.items():
    print(i,j)
#note: the above two practices, their result are some what different, just check

Output:


Key names using keys() method are:
name
age
city
color
origin
religion
colors

Key names using items() method are:
('name', 'Leyla Ali')
('age', 45)
('city', 'London')
('color', 'Blck')
('origin', 'Nigeria')
('religion', 'Islam')
('colors', {'yellow', 'marron', 'red', 'green'})

Key names without using any method are:
name
age
city
color
origin
religion
colors

Value items using values() method are:
Leyla Ali
45
London
Blck
Nigeria
Islam
{'yellow', 'marron', 'red', 'green'}

Value items using indexing technique
Leyla Ali
45
London
Blck
Nigeria
Islam
{'yellow', 'marron', 'red', 'green'}

Value items using keys method and ndexing technique
Leyla Ali
45
London
Blck
Nigeria
Islam
{'yellow', 'marron', 'red', 'green'}

Value items using items method and ndexing technique
('name', 'Leyla Ali')
('age', 45)
('city', 'London')
('color', 'Blck')
('origin', 'Nigeria')
('religion', 'Islam')
('colors', {'yellow', 'marron', 'red', 'green'})

Value items using items method and ndexing technique
name Leyla Ali
age 45
city London
color Blck
origin Nigeria
religion Islam
colors {'yellow', 'marron', 'red', 'green'}

Dictionary Comprehension

Similar to other sequences of data structure such as list comprehensions, Python also provides dictionary comprehensions. This support allows you to create dictionaries in a concise and readable manner.

Example:


# Dictionary Comprehension
numbers = [1, 2, 3, 4, 5, 6]
square_dict = {num: num * 5 for num in numbers}

print(square_dict)
print(type(square_dict))

Output:


{1: 5, 2: 10, 3: 15, 4: 20, 5: 25, 6: 30}
<class 'dict'>

When you run the above Python code, you will see an output which is a dictionary where each number from 1 to 6 is a key, and the corresponding value is that number multiplied by 5.

Dictionary Methods Python Supports

Python comes with number of methods supported in dictionaries, these are built-in methods which is used to perform various operations efficiently. Here are some of them.

Dictionary get() method

get() Method is a simple built in method that returns the value after you specified specified its key.

Example, you want to return the value of the “name” item or “age” item:

Example:


# Dictionary Methods
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

# Get the value for a key using get() method
print(my_dict.get('name'))  
print(my_dict.get('age'))  
print(my_dict.get('city'))  

# this will not be stored but only return
print(my_dict.get('new item',67))      

# it will print None, because does not exist
print(my_dict.get(30)) 

Output:


John
30
New York
67
None

Remember, the get() method provides a way to safely retrieve values from dictionaries, avoiding KeyError exceptions when keys are not found. It also allows for specifying a default value if the key does not exist.

for Handling Non-existent Keys without a Default Value: the get() method returns None if the key is not found and no default value is provided. see this code: print(my_dict.get(30))

Dictionary keys() Method

The keys() method is a built-in method in Python dictionaries that returns a view object representing the keys of the dictionary.

We use this method to iterate over the keys of a dictionary or to obtain a list of keys for further processing. It’s syntax is like this dictionary.keys()

Example:


# Dictionary Methods
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

# Get a list of keys
print(my_dict.keys())  

# you can also store the return data into a variable
keys_view = my_dict.keys()

print(keys_view)  # Output: dict_keys(['a', 'b', 'c'])

# Iterating over the keys
for key in my_dict.keys():
    print(key)

Output:


dict_keys(['name', 'age', 'city'])
dict_keys(['name', 'age', 'city'])
name
age
city

Dictionary values() Method

The values() Method which is used in dictionary is a built-in method supported in Python dictionaries which returns a view object representing the values of the dictionary.

We normally use this method to iterate or loop over the values of a dictionary in order to get a list of values for further processing. Let me show an example of that.

the syntax of values() Method is like this: dictionary.values()

Example:


# Dictionary Methods
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

# Get a list of values
print(my_dict.values())  

# you can also store the return data into a variable
values_view = my_dict.values()

print(values_view)  

# Iterating over the values
for values in my_dict.values():
    print(values)

Output:


dict_values(['John', 30, 'New York'])
dict_values(['John', 30, 'New York'])
John
30
New York

Dictionary clear() Method

The clear() method in Python is is a built-in method in Python dictionaries which is used to remove all items (key-value pairs) from a dictionary. It effectively empties the dictionary, making it an empty container.

Note: Make sure you don’t apply this into real live project as you might lose some data.

We aim to use this method when we want to reset a dictionary or remove all its contents.

It’s Syntax is as follows: dictionary.clear()

Example:


# Dictionary Methods
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

# before it is removed
print(my_dict) 

# Remove all items
my_dict.clear()

# after it has been removed
print(my_dict) 

Output:


{'name': 'John', 'age': 30, 'city': 'New York'}
{}

Dictionary update() Method

Python also provides a method called update() which is built-in method and it is used to update a dictionary with the key-value pairs from another dictionary or from an iterable of key-value pairs (such as a list of tuples).

Note: If a key exists in both dictionaries, the value from the other dictionary will overwrite the value of the existing key in the original dictionary.

We use this method to merge or update one dictionary with the contents of another dictionary.

The syntax for the update() method is as follows: dictionary.update(iterable)

Example:


# update() method
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

# before updated or added new item in dictionary
print(my_dict)

# Add items using assignment
my_dict['student'] = False

# if the key does not exist it will be treated as new one and it will be added in the dictionary
my_dict.update({'race': 'Canadian'})

print(my_dict)

# check this way also
my_dict1 = {'a': 1, 'b': 2}
my_dict2 = {'b': 3, 'c': 4}

my_dict1.update(my_dict2)
print(my_dict1) 

# Updating with an iterable (list of tuples)
my_dict3 = {'d': 5, 'e': 6}
my_dict1.update([('f', 7), ('g', 8)])
print(my_dict1) 

Output:


{'name': 'John', 'age': 30, 'city': 'New York'}
{'name': 'John', 'age': 30, 'city': 'New York', 'student': False, 'race': 'Canadian'}
{'a': 1, 'b': 3, 'c': 4}
{'a': 1, 'b': 3, 'c': 4, 'f': 7, 'g': 8}

Merge or Combine Dictionaries

Another way of using the update() method is to combine or merge different dictionaries. This means using such method we can merge two dictionaries using the update() method or dictionary unpacking (** operator).

Example:


# Merge Dictionaries
dict1 = {'name': 'John', 'age': 30}
dict2 = {'city': 'New York'}

# Using update() method
dict1.update(dict2)
print(dict1)  # Output: {'name': 'John', 'age': 30, 'city': 'New York'}

# Using dictionary unpacking
dict3 = {**dict1, **dict2}
print(dict3)  # Output: {'name': 'John', 'age': 30, 'city': 'New York'}

# update() method
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

# before updated or added new item in dictionary
print(my_dict)

# Add items using assignment
my_dict['student'] = False

# if the key does not exist it will be treated as new one and it will be added in the dictionary
my_dict.update({'race': 'Canadian'})

print(my_dict)

# check this way also
my_dict1 = {'a': 1, 'b': 2}
my_dict2 = {'b': 3, 'c': 4}

my_dict1.update(my_dict2)
print(my_dict1) 

# Updating with an iterable (list of tuples)
my_dict3 = {'d': 5, 'e': 6}
my_dict1.update([('f', 7), ('g', 8)])
print(my_dict1) 

Output:


{'name': 'John', 'age': 30, 'city': 'New York'}
{'name': 'John', 'age': 30, 'city': 'New York', 'student': False, 'race': 'Canadian'}
{'a': 1, 'b': 3, 'c': 4}
{'a': 1, 'b': 3, 'c': 4, 'f': 7, 'g': 8}
{'name': 'John', 'age': 30, 'city': 'New York'}
{'name': 'John', 'age': 30, 'city': 'New York'}

Perform Operations in Python Dictionaries

If we want to perform some operations in Python Dictionaries, don’t worry Python supports or provides various operations, including joining dictionaries, comparing dictionaries, performing mathematical operations, and eliminating duplicates and others.

Consider the following example and try to practice by yourself.

Example:


# Perform Operations in Dictionaries

# Join Dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
joined_dict = {**dict1, **dict2}
print(joined_dict) 

# Multiply Dictionaries
# multiplied_dict = dict1 * 2  # Error: unsupported operand type(s) for *: 'dict' and 'int'

# Compare Dictionaries
dict3 = {'a': 1, 'b': 2}
dict4 = {'b': 2, 'a': 1}
print(dict3 == dict4)  

# Perform Mathematical Operation in Dictionaries
math_dict = {'a': 10, 'b': 20, 'c': 30}
sum_values = sum(math_dict.values())
print(sum_values) 

# Eliminate Duplicates in Dictionaries
duplicates_dict = {'a': 1, 'b': 2, 'c': 1, 'd': 2}
unique_dict = {key: value for key, value in duplicates_dict.items()}
print(unique_dict) 

Output:


{'a': 1, 'b': 2, 'c': 3, 'd': 4}
True
60
{'a': 1, 'b': 2, 'c': 1, 'd': 2}

Conclusion

Let us conclude, in this course, we have explained and provided various examples and subtopics related to Python dictionaries which is versatile data structures and it allow us to store key-value pairs efficiently.

The Python dictionary mainly offers various methods and operations to manipulate and access its data very quickly and smoothly. I believe, you understood the fundamentals of dictionaries and their functionalities, so now you can enhance your Python programming skills and build more robust applications.

I suggest you to keep practicing and exploring different scenarios in order to master dictionary manipulation in Python. Go and find other related data structures and also learn the difference between them such as (Tuples, List, Sets etc). With time and experience, you will become proficient in using dictionaries to solve a wide range of programming challenges.

Categorized in: