Iterate through dictionary Python

In this Python tutorial, we will study how to iterate through a dictionary in Python using some examples in python. Moreover, we will also cover these topics.

  • Iterate through dictionary Python with index
  • Iterate through dictionary Python for loop
  • Iterate through dictionary Python reverse
  • Iterate through dictionary Python sorted
  • Iterate through dictionary Python in order
  • Iterate through dictionary Python lambda
  • Iterate through dictionary Python with multiple values
  • Iterate through dictionary Python with list
  • Python iterate through dictionary within dictionary
  • Python iterate through dictionary of dataframes
  • Python iterate through dictionary and remove items
  • Python iterate through dictionary and change values
  • Python iterate through dictionary sorted by key
  • Python iterate through dictionary sorted by value

Python iterate through dictionary Python

  • In this section, we will discuss how to iterate through a dictionary in Python.
  • To iterate through a dictionary we can easily use the dictionary.items() method and it will always return iterable objects like lists and tuples in the form of key-value pairs.
  • In Python dictionary, the dict.items() method is used to display a list of dictionary elements in the form of key-value pair and this method is available in the Python package module.

Syntax:

Let’s have a look at the syntax and understand the working of dict.items() function

dictionary.items()

Example:

Let’s take an example and check how to iterate a dictionary in Python.

Source Code:

my_dictionary = {'USA': 678, 'Germany': 145, 'France': 789}

for m in my_dictionary.items():
    print("Iterate dictionary elements:",m)

In the above code, we have created a simple dictionary named ‘my_dictionary’ which contains elements in the form of key-value pairs. After that, we have used the for loop method to iterate through the key-value pair and it will operate both keys and values and return in the form of tuples.

Here is the Screenshot of the following given code.

Iterate through dictionary Python
Iterate through dictionary Python

Read: Python Dictionary duplicate keys

Iterate through dictionary Python with index

  • Here we are going to iterate the dictionary by using the index method in Python.
  • To perform this particular task, we are going to use the for loop method and it will iterate all the elements which are available in the given dictionary.
  • In for-loop, we have run the enumerator function and this method takes an iterable object like dictionary and list as an argument and returns enumerate an object in this example these functions return keys along with index position.

Example:

new_dictionary = {'George': 134, 'John': 245, 'James': 120}

for new_indices, new_k in enumerate(new_dictionary):
    print('Iterate dictionary: ', new_indices, ' :- ', new_k)

Here is the execution of the following given code

Iterate through dictionary with index in Python
Iterate through the dictionary with index in Python

Read: Python Dictionary Count + Examples

Iterate through dictionary Python for loop

  • In this Program, we will discuss how to iterate a dictionary in Python by using for loop method.
  • This method will help the user to iterate each value and key in the dictionary. For example, suppose you have a dictionary that contains fruits elements in the form of key-value pair and you want to print out the keys and values of a specific fruit name.

Example:

Fruit={'Orange':567,'Mango':134,'Cherry':167}

for i in Fruit:
	print(i, Fruit[i])

In the following given code, we have created a dictionary ‘Fruit’ that contains elements in the form of key-value pairs. After that, we have used the for loop and iterate each value in the dictionary.

Here is the implementation of the following given code.

Iterate through dictionary Python for loop
Iterate through dictionary Python for loop

Read: Python dictionary increment value

Iterate through dictionary Python reverse

  • In this section, we will discuss how to reverse the elements by iterating through the dictionary in Python.
  • To iterate over the dictionary elements, we can easily use the list comprehension method along with dict.items() and it will return a reverse order element.
  • Suppose you have specified the elements in the form of a key: value pair. Once you will apply this function then it will reverse the elements in the form of value: key pairs.

Syntax:

Here is the Syntax of the Python dictionary.items() function

dictionary.items()

Example:

Let’s take an example and check how to reverse the elements by iterating through the dictionary in Python

Source Code:

my_dictionary={'USA':345,'United Kingdom':789,'Germany':145,'France':654}

print("Original dictionary:",my_dictionary)
new_result={new_val:new_key for new_key,new_val in my_dictionary.items()}
print("Iterate reversed dictionary:",new_result)

In the following given code, we have created a dictionary named ‘my_dictionary’ and then use the list comprehension method in which we have to assign the key and value variable to iterate with a given dictionary.

Here is the Output of the following given code.

Iterate through dictionary Python reverse
Iterate through dictionary Python reverse

Read: Python dictionary of lists – Detailed Guide

Iterate through dictionary Python sorted

  • In this section, we will discuss how to sort the elements by iterating through the dictionary in Python.
  • To perform this particular task we are going to use the sorted() function and this method will always return a list with the values in a sorted manner. In this example, we will sort first, and then we will iterate the values by using the for-loop method.
  • In this example first, we will sort the keys by using the sorted(dict.keys()) method and this function will always return all the keys which is available in the dictionary then we are going to sort all the values by using sorted(dict.values()) method.

Syntax:

Here is the Syntax of the Python dictionary.keys() method

dict.keys() 

Example:

my_dictionary={'USA':345,'United Kingdom':789,'Germany':145,'France':654}

for new_k in sorted(my_dictionary.keys()):
    print("Sorted keys:",new_k, ':', my_dictionary[new_k])
for new_val in sorted(my_dictionary.values()):
     print("Sorted values:",new_val)

Here is the Screenshot of the following given code.

Python iterate through dictionary sorted
Python iterate through dictionary sorted

As you can see in the Screenshot the output displays the sorted keys and values.

Read: Python Dictionary Copy with Examples

Iterate through dictionary Python in order

  • In this section, we will discuss how to iterate a dictionary in order method.
  • In this example, we are going to use the list comprehension method and within this function, we have set the key and value variable for iterating the dictionary values and then use the dict.items() method.

Example:

my_dictionary={'Newzealand':345,'Australia':345,'Paris':897,'France':234}

for new_k, new_val in sorted(my_dictionary.items()):
        print((new_k, new_val))

Here is the implementation of the following given code.

iterate through dictionary Python in order
iterate through dictionary Python in order

Read: Python dictionary multiple keys

Iterate through dictionary Python lambda

  • In this section, we will discuss how to use the lambda function for iterating through a dictionary in Python.
  • In this example, we are going to use the lambda expression for declaring an inline function where new_k is the parameter of lambda and the map function executes a lambda function and it will return all the keys in the list.

Example:

my_dictionary={'Newzealand':345,'Australia':345,'Paris':897,'France':234}

new_result = list(map(lambda new_k: my_dictionary[new_k], my_dictionary.keys()))
print("Iterate values using lambda:",new_result)

In the above code, we have created a dictionary named ‘my_dictionary’ that contains elements in the form of key-value pairs. After that, we have used the lambda function along with the dictionary.keys() method and it will iterate the keys of the given dictionary and store them into the list.

Here is the Screenshot of the following given code.

iterate through dictionary Python lambda
iterate through dictionary Python lambda

Read: Python Dictionary to CSV

Iterate through dictionary Python with multiple values

  • In this section, we will learn how to iterate a dictionary in Python with multiple values.
  • To perform this particular task we are going to use the list comprehension method and it will iterate all list values for a given key. In this example, we will create a dictionary that will assign the key with multiple values.
  • Next, we will iterate the dictionary by using for loop and items() method and it will iterate all the items in that list.

Example:

Let’s take an example and check how to iterate a dictionary in Python with multiple values

new_dictionary = {'USA':[23,67,89,12]}

new_list=[]
new_list = [[new_k,new_val] for new_k, values in new_dictionary.items() for new_val in values]
print("Iterate multiple values in dictionary:",new_list)

In the following given code, we have created a dictionary named ‘new_dictionary’ that contains a single key with multiple values. After that, we have created an empty list in which all the values can be stored by using for loop and dict.items() method.

Once you will execute this code the output displays the list of pairs where the key remains the same and values are different.

Here is the Screenshot of the following given code.

Iterate through dictionary Python with multiple values
Iterate through dictionary Python with multiple values

Read: Python convert dictionary to an array

Iterate through dictionary Python with list

  • In this section, we will discuss how to iterate a dictionary in Python with list.
  • By using the list comprehension method we can easily iterate the dictionary with the list. To do this task first we will create a dictionary and assign key-value pairs and values that can be stored in the list.
  • Next for iterating the values and keys, we are going to use the for loop method and dict.keys() method.

Example:

new_dictionary = {'USA' : [24,36,16], 'United Kingdom' : [89, 24,56], 'France' : [97,56,66]}

new_output = [[m for m in new_dictionary[new_k]] for new_k in new_dictionary.keys()]
print("Iterate dictionary with lists:",new_output)

Here is the implementation of the following given code.

Iterate through dictionary Python with list
Iterate through dictionary Python with list

Read: Get all values from a dictionary Python

Python iterate through dictionary within dictionary

  • Here we are going to discuss how to iterate a nested dictionary in Python.
  • To perform this particular task, we are going to use the for loop and dict.items() method and it will iterate all the values in the nested dictionary.
  • In Python, the nested dictionary specifies the dictionary within the dictionary and it is an unordered collection of items.
  • In this example, there are two dictionaries each having its own key and value and now I want to iterate all elements of the given nested dictionary.

Example:

Let’s take an example and check how to iterate a nested dictionary in Python.

Source Code:

Country_name = {'A': {'Germany': 67, 'France': 456, 'Polland': 456},
          'B': {'China': 456, 'Australia': 789, 'Japan': 567}}

for new_k, new_val in Country_name.items():
    print(new_k)
    
    for i in new_val:
        print(i + ':-', new_val[i])

In the above code, we have created a nested dictionary named ‘Country_name’, and the internal dictionary ‘A’ and ‘B’ are assigned to ‘Country_name’.

After that, we have a key name as countries name along with their random values. By using for loop and dict.items() method, we can easily extract the values from a list.

Here is the execution of the following given code.

Python iterate through dictionary within dictionary
Python iterate through dictionary within a dictionary

Read: Python creates a dictionary from two lists

Python iterate through dictionary of dataframes

  • In this Program, we will discuss how to iterate a dictionary and convert them into Pandas dataframe.
  • In Python Pandas DataFrame is a structure that computes in two dimension rows and columns.
  • In this example first, we will import the Pandas library and then we are going to create a dictionary that contains elements in the form of key-value pairs. To iterate the dictionary we will use the for loop method and it will help the user to iterate all the values in the dictionary.
  • Next, we will use the Pd.dataframe and assign the iterable attribute ‘i’ as an argument and it will easily convert into a dataframe.

Example:

Let’s take an example and check how to iterate a dictionary and convert them into Pandas DataFrame.

Source Code:

import pandas as pd

dict={'Student_name':'John','Student_id':456,'Student_age':234}
for i in dict.items():
   print(pd.DataFrame(i))

Here is the Screenshot of the following given code

Python iterate through dictionary of dataframes
Python iterate through a dictionary of data frames

Read: Python dictionary contains + examples

Python iterate through dictionary and remove items

  • In this section, we will learn how to iterate a dictionary and remove items from Python dictionary.
  • To do this task we are going to use the for loop method for iterating the dictionary elements and to remove items from the dictionary we will use the del keyword.
  • In Python, the del is used to delete the specific items from iterable objects like dictionaries and this keyword is available in the Python dictionary package.

Syntax:

Let’s have a look at the syntax and understand the working of the del keyword

del[object name]

Example:

Let’s take an example and check how to iterate a dictionary and remove items from the dictionary.

Source Code:

my_dictionary={'Cherry':234,'Apple':453,'Mango':13,'Grapes':12}

for new_k, new_val in dict(my_dictionary).items():
    if new_val % 3 == 0:
        del my_dictionary[new_k]
print(my_dictionary) 

In the following given code, we have created a dictionary that contains key-value pairs. After that, we have used the for loop method along with dict.items() function and it will iterate all the elements in the dictionary.

After iterating all the elements we have set the condition if new_val %3==0 and it will check the condition if the values are divided by 3 then it will remove from a dictionary and those who are not divided by 3 then it will return into tuple form.

Here is the implementation of the following given code

Python iterate through dictionary and remove items
Python iterate through a dictionary and remove items

Read: Python dictionary comprehension

Python iterate through dictionary and change values

  • Here we are going to discuss how to iterate and change values in Python dictionary.
  • To iterate the elements in the dictionary, we are going to use the for loop method and for updating the values we will use the ‘if’ condition.

Example:

dictionary = {'Africa':200,'australia':300,'England':400}

for new_k, new_values in dictionary.items():
    if new_values==300:
        dictionary[new_k] = 600
print(dictionary)

In the above code, we have created a dictionary that contains elements in the form of key-value pairs. After that, we have used the for-loop method for iterating the elements and set the condition if new_values==300, and it will check the condition if 300 value is available then it will update with 600 value.

You can refer to the below Screenshot.

Python iterate through dictionary and change values
Python iterate through dictionary and change values

Read: Python dictionary remove

Python iterate through dictionary sorted by key

  • In this section, we will learn how to iterate a dictionary and sorted by key in Python.
  • To iterate through a dictionary in Python we are going to use the for-loop method and to get the sorted keys we can easily use the sorted() function and within this function, we will assign the dictionary as an argument.
  • In Python, the sorted() function is used to sort the values of a given iterable-like object. Once you will execute this code the output displays the sorted keys as per the requirement.

Example:

Let’s take an example and check how to iterate a dictionary and sort by key in Python.

Source Code:

dictionary = {'George':200,'Micheal':300,'Oliva':400,'James':345}

for new_k in sorted (dictionary):
    print("Sorted keys by iterating dictionary:",new_k)

Here is the Screenshot of the following given code.

Python iterate through dictionary sorted by key
Python iterate through dictionary sorted by key

Read: Python Dictionary index – Complete tutorial

Python iterate through dictionary sorted by value

  • In this Program, we will learn how to iterate through dictionary and sorted by value in Python.
  • To perform this particular task we are going to use the sorted() function along with dict.values() method. To sort the items of a dictionary by values we can use the dict.values() in the sorted() function as an argument.
  • In Python, this method is available in dictionary modules and it is used to extract the values in the dictionary.

Syntax:

Here is the Syntax of dict.values() method

dict.values()

Example:

new_dict = {'Australia':200,'Germany':300,'France':400,'Polland':345}

for new_k in sorted (new_dict.values()):
    print("Sorted keys by iterating dictionary:",new_k)

Here is the execution of the following given code.

Python iterate through dictionary sorted by value
Python iterate through dictionary sorted by value

You may also like to read the following Python tutorials.

In this Python tutorial, we have learned how to iterate through a dictionary in Python using some examples in python. Moreover, we have also covered these topics.

  • Iterate through dictionary Python with index
  • Iterate through dictionary Python for loop
  • Iterate through dictionary Python reverse
  • Iterate through dictionary Python sorted
  • Iterate through dictionary Python in order
  • Iterate through dictionary Python lambda
  • Iterate through dictionary Python with multiple values
  • Iterate through dictionary Python with list
  • Python iterate through dictionary within dictionary
  • Python iterate through dictionary of dataframes
  • Python iterate through dictionary and remove items
  • Python iterate through dictionary and change values
  • Python iterate through dictionary sorted by key
  • Python iterate through dictionary sorted by value