Python iterate dictionary with index

Python: Iterate over dictionary with index

In this article, we will discuss different ways to iterate over a dictionary by index.

Table of Contents

For iterating over a sequence by indexing, we can use the function enumerate() in python.

Overview of enumerate():

The enumerate() function in python provides a way to iterate over a sequence by index.

Frequently Asked:

  • iterable: An iterable sequence over which we need to iterate by index.
  • start: An int value.
    • It is the counter from which indexing will start.

    It yields a pair of counter and item from the iterable. We can use it to iterate over the iterable sequence and but now along with item we will get the index position of the item while iteration.

    Let’s use this to iterate over a dictionary by index,

    Iterate over all key-value pairs of dictionary by index

    The items() function of dictionary class returns an iterable sequence of all key value pairs of the dictionary. We can pass that to the enumerate() function to yields key-value pairs along with index position. For example,

    # A dictionary of string and integers word_freq = < 'Hello' : 56, "at" : 23, 'test' : 43, 'This' : 78, 'Why' : 11 ># Iterate over all key-value pairs of dictionary by index for index, (key, value) in enumerate(word_freq.items()): print('Index:: ', index, ' :: ', key, '-', value)
    Index:: 0 :: Hello - 56 Index:: 1 :: at - 23 Index:: 2 :: test - 43 Index:: 3 :: This - 78 Index:: 4 :: Why - 11

    As we passed the sequence returned by items() to the enumerate() function with start index 0 (default value). Therefore it yielded each item (key-value) of dictionary along with index, starting from 0.

    Iterate over all keys of dictionary by index

    The keys() function of dictionary class returns an iterable sequence of all keys of the dictionary. We can pass that to the enumerate() function to yields keys along with index position. For example,

    # A dictionary of string and integers word_freq = < 'Hello' : 56, "at" : 23, 'test' : 43, 'This' : 78, 'Why' : 11 ># Iterate over all keys of dictionary by index for index, key in enumerate(word_freq): print('Index:: ', index, ' :: ', key)
    Index:: 0 :: Hello Index:: 1 :: at Index:: 2 :: test Index:: 3 :: This Index:: 4 :: Why

    As we passed the sequence returned by keys() to the enumerate() function with start index 0 (default value). Therefore it yielded each key of the dictionary along with index, starting from 0.

    While iterating over all keys with index position, we can also fetch the value associated with the key. For example,

    # A dictionary of string and integers word_freq = < 'Hello' : 56, "at" : 23, 'test' : 43, 'This' : 78, 'Why' : 11 ># Iterate over all key-value pairs of dictionary by index for index, key in enumerate(word_freq): print('Index:: ', index, ' :: ', key, ' , ', word_freqPython iterate dictionary with index)
    Index:: 0 :: Hello , 56 Index:: 1 :: at , 23 Index:: 2 :: test , 43 Index:: 3 :: This , 78 Index:: 4 :: Why , 11

    Iterate over all values of dictionary by index

    The values() function of dictionary class returns an iterable sequence of all values of the dictionary. We can pass that to the enumerate() function to yields values along with index position. For example,

    # A dictionary of string and integers word_freq = < 'Hello' : 56, "at" : 23, 'test' : 43, 'This' : 78, 'Why' : 11 ># Iterate over all values of dictionary by index for index, value in enumerate(word_freq.values()): print('Index:: ', index, ' :: ', value)
    Index:: 0 :: 56 Index:: 1 :: 23 Index:: 2 :: 43 Index:: 3 :: 78 Index:: 4 :: 11

    As we passed the sequence returned by values() to the enumerate() function with start index 0 (default value). Therefore it yielded each value of the dictionary along with index, starting from 0.

    We learned, how to iterate over a dictionary in python with indexing. We can either iterate over all key-value pairs or only keys or values with indices.

    Share your love

    Leave a Comment Cancel Reply

    This site uses Akismet to reduce spam. Learn how your comment data is processed.

    Terms of Use

    Disclaimer

    Copyright © 2023 thisPointer

    To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

    Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

    The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

    The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

    The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

    The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

    Источник

    Python iterate dictionary with index – Python: Iterate Over Dictionary with Index

    BTech Geeks

    Python iterate dictionary with index: Dictionaries are the implementation by Python of a knowledge structure associative array. A dictionary is a collection of pairs of key values. A key pair and its associated value represent each key pair.
    The list of key value pairs in curly braces that’s separated by comma defines a dictionary. Column ‘:’ separates the value of each key.
    A dictionary can’t be sorted only to urge a representation of the sorted dictionary. Inherently, dictionaries are orderless, but not other types, including lists and tuples. Therefore, you would like an ordered data type, which may be a list—probably an inventory of tuples.

    index = 0 ; key = this ; Value = 200 index = 1 ; key = is ; Value = 100 index = 2 ; key = BTechGeeks ; Value = 300

    Traverse the Dictionary with Index

    1)Enumerate() function:

    How to iterate over a dictionary in python: When working with iterators, we frequently encounter the need to keep track of the number of iterations. Python makes it easier for programmers by providing a built-in function enumerate() for this purpose.
    Enumerate() adds a counter to an iterable and returns it as an enumerate object. This enumerate object can then be utilized in for loops directly or converted into an inventory of tuples using the list() method.

    iterable: an iterator, a sequence, or objects that support iteration start : the index value from which the counter will be started; the default value is 0.
    The method enumerate() adds a counter to an iterable and returns it. The object returned is an enumerate object.

    2)Traverse over all key-value pairs of given dictionary by index

    We can traverse over the dictionary by passing given dictionary as parameter in enumerate() function

    Below is the implementation:

    # given dictionary dictionary = # Traverse all key-value pairs of given dictionary by index for i, key in enumerate(dictionary): print('index =', i, ' ; key =', key, ' ; Value =', dictionaryPython iterate dictionary with index)
    index = 0 ; key = this ; Value = 200 index = 1 ; key = is ; Value = 100 index = 2 ; key = BTechGeeks ; Value = 300

    3)Traverse over all keys of given dictionary by index

    The dictionary class’s keys() function returns an iterable sequence of all the dictionary’s keys. We can pass that to the enumerate() function, which will return keys as well as index position.

    Below is the implementation:

    # given dictionary dictionary = # Traverse all keys of given dictionary by index for i, key in enumerate(dictionary.keys()): print('index =', i, ' ; key =', key)
    index = 0 ; key = this index = 1 ; key = is index = 2 ; key = BTechGeeks

    4)Traverse over all values of given dictionary by index

    The dictionary class’s values() function returns an iterable sequence of all the dictionary’s values. We can pass that to the enumerate() function, which will return values as well as index position.

    Below is the implementation:

    # given dictionary dictionary = # Traverse all values of given dictionary by index for i, value in enumerate(dictionary.values()): print('index =', i, ' ; value =', value)
    index = 0 ; value = 200 index = 1 ; value = 100 index = 2 ; value = 300

    Related Programs:

    Источник

    Читайте также:  Error code 1625 java
Оцените статью