How to Iterate Through a Dictionary in Python

Posted in /   /  

How to Iterate Through a Dictionary in Python

Vinay Khatri
Last updated on June 10, 2022

    Dictionaries are one of the most prominent and often used Python Data structure. A Python dictionary is used to solve and implement many problems. In this tutorial, we will look at how to iterate through a dictionary in Python. By the end of this article you will have a brief idea about:

    • What is a Dictionary in python?
    • How to iterate through a dictionary
    • Different techniques to iterate through a dictionary.

    Python Dictionary

    Dictionary is a built-in Data Structure in Python, and like other data structure, it is used to store values in a specified manner. Python dictionary uses a hash memory system, in which it stores elements or data objects in the form of key:value pair. Where each key is mapped to its corresponding value like a hash table. Example

    my_dict = {1:"One", 2:"Two", 3:"Three"}

    Dictionaries are used to solve many problems and using a dictionary you can create graphs and tree data structures with ease. Accessing an element from a dictionary is also very easy however it follows a similar syntax to list but instead of using integer indices, in the dictionary, we index the value by its key. Example

    >>> my_dict = {1:"One", 2:"Two", 3:"Three"}
    >>> my_dict[1]
    'One'

    Dictionary is an unordered data structure which means it is not necessary that you will get the key:value pair in the same order in which they were created. Example

    >>>my_dict = {1:"One", 2:"Two", 3:"Three", 4:"Four", 5:"five"}
    >>> my_dict
    {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'five'}

    <Note>: For a small set of elements the order of sequence may be the same but it won’t be the same for large number of elements.

    How to Iterate Through a Dictionary in Python

    When you work on a Python project you will be using Python dictionaries a lot, because is provide a very elegant way to represent data values. So as a Python coder or programmer you should know all the techniques by which you can iterate through a dictionary and get the output you desire.

    Iterating Through Dictionaries Keys

    When we use the direct for loop to iterate through a dictionary, we generally iterate through dictionary keys. With every for-loop statement, we go through the dictionary key and grab every key name. Example

    my_dict = {"host": "TechGeekBuzz",
               "topic":"dictionary",
               "language":"Python",
               "section":"Tutorial"
              }
    
    for key in my_dict:
        print(key)

    Output

    host
    topic
    language
    section

    As for loop can help us to go through every key of the dictionary, then using the keys we can access its corresponding value. Example

    my_dict = {"host": "TechGeekBuzz",
               "topic":"dictionary",
               "language":"Python",
               "section":"Tutorial"
              }
    for key in my_dict:
        print(key,":", my_dict[key])

    Output

    host : TechGeekBuzz
    topic : dictionary
    language : Python
    section : Tutorial

    Iterate Through Dictionary items using .item() method

    When we work with dictionaries and want to grab both keys as well as values at the same time, we can use the dictionary .items() method. The item() is an in-built dictionary method that returns a list of paired tuples, where the tuple first element represents the key and the second represents the corresponding value. Example

    my_dict = {"key1":"Value1", "Key2":"Value2", "Key3":"Value3", "Key4":"Value4", "key5":"Value5"}
    
    >>> my_dict.items()
    dict_items([('key1', 'Value1'), ('Key2', 'Value2'), ('Key3', 'Value3'), ('Key4', 'Value4'), ('key5', 'Value5')])

    Then using the tuple unpacking we can collect the key and its corresponding value simultaneously. Example

    my_dict = {"host": "TechGeekBuzz",
               "topic":"dictionary",
               "language":"Python",
               "section":"Tutorial"
              }
    
    for key,value in my_dict.items():
        print(key,":",value)

    Output

    host : TechGeekBuzz
    topic : dictionary
    language : Python
    section : Tutorial

    Iterate Through .keys() method

    The .keys() is another dictionary inbuilt method which returns a list containing all the keys of the specified dictionary. Example

    >>> my_dict = {"key1":"Value1", "Key2":"Value2", "Key3":"Value3", "Key4":"Value4", "key5":"Value5"}
    >>> my_dict.keys()
    dict_keys(['key1', 'Key2', 'Key3', 'Key4', 'key5'])

    You can use this method when you want to collect all the keys from the dictionary. Example

    my_dict = {"host": "TechGeekBuzz",
               "topic":"dictionary",
               "language":"Python",
               "section":"Tutorial"
              }
    for key in my_dict.keys():
        print(key)

    Output

    host
    topic
    language
    section

    Iterate Through .values()

    Like the keys() method dictionary also provides us with .values() method, that returns a list of all the values present in the dictionary. Example

    >>> my_dict = {"key1":"Value1", "Key2":"Value2", "Key3":"Value3", "Key4":"Value4", "key5":"Value5"}
    >>> my_dict.values()
    dict_values(['Value1', 'Value2', 'Value3', 'Value4', 'Value5'])

    And if you only want to iterate through dictionary values then you can use this method. Example

    my_dict = {"host": "TechGeekBuzz",
               "topic":"dictionary",
               "language":"Python",
               "section":"Tutorial"
              }
    
    for value in my_dict.values():
        print(value)

    Output

    TechGeekBuzz
    dictionary
    Python
    Tutorial

    Membership Test using in Operator

    By default the in operator checks for the dictionary keys membership, but if you want to use in operator for the dictionary values then you can use the values() method. Example

    my_dict = {"host": "TechGeekBuzz",
               "topic":"dictionary",
               "language":"Python",
               "section":"Tutorial"
              }
    
    #check for the key
    print("host" in my_dict)
    
    #check for the value
    print("Python" in my_dict.values())

    Output

    True
    True 

    Sort the Dictionary by its Keys

    It’s very easy to sort a Dictionary by its keys, you just need to use the Python sorted method and your dictionary will be sorted based on the keys. The sorted method would return a list of sorted dictionary keys. Example

    my_dict = {"host": "TechGeekBuzz",
              "topic":"dictionary",
              "language":"Python",
              "section":"Tutorial"
             }
    for key in sorted(my_dict):
        print(key,":", my_dict[key] )

    Output

    host : TechGeekBuzz
    language : Python
    section : Tutorial
    topic : dictionary

    In this example, the sorted() method sort the keys on the basis of alphanumerical order.

    Sort the dictionary by its values

    Sorting a dictionary by its values could be a little tricky . But there are two naïve and easy ways to sort a dictionary by its value. In the first techniques, we can directly apply the sorted() function on the my_dict.values(). But here we will fail to grab the key for the values. Example

    my_dict = {"host": "TechGeekBuzz",
               "topic":"Dictionary",
               "language":"Python",
               "section":"Tutorial"
              }
    
    for values in sorted(my_dict.values()):
        print(values )

    Output

    Dictionary
    Python
    TechGeekBuzz
    Tutorial

    In the other approach we use the sorted() function on the .items() method, and sorted() set the key parameter. Example

    my_dict = {"host": "TechGeekBuzz",
               "topic":"Dictionary",
               "language":"Python",
               "section":"Tutorial"
             }
    
    def byValues(item):
        return item[1]
    
    for key, value in sorted(my_dict.items(), key= byValues):
        print(key, ":" , value)

    Output

    topic : Dictionary
    language : Python
    host : TechGeekBuzz
    section : Tutorial

    By setting the key= byValues , we specified that use the byValues() function for sorting reference. And the byValues(item) function returns the second value for every tuple which specifies that sort the give iterable based on the second value.

    Conclusion

    In this Python tutorial you learned, how to iterate through a Dictionary in Python and how it works with for loop statement. By default the for loop iterates through dictionary keys, but it can be changed using some methods like values() and items(). If you liked this article or have any queries related to the Python dictionary please let us know by commenting down below. People are also reading:

    Leave a Comment on this Post

    0 Comments