Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate `dict` with `enumerate` and unpack the index, key, and value along with iteration

How to iterate dict with enumerate such that I could unpack the index, key and value at the time of iteration?

Something like:

for i, (k, v) in enumerate(mydict):     # some stuff 

I want to iterate through the keys and values in a dictionary called mydict and count them, so I know when I'm on the last one.

like image 814
themink Avatar asked Feb 12 '17 21:02

themink


People also ask

How do you iterate through keys and values in a dictionary?

In order to iterate over the values of the dictionary, you simply need to call values() method that returns a new view containing dictionary's values.

How do you iterate over an index in a dictionary?

Iterate over all key-value pairs of dictionary by index 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.

Which method allows us to access both key and value on a dictionary at the same time in Python?

items() , in dictionary iterates over all the keys and helps us to access the key-value pair one after the another in the loop and is also a good method to access dictionary keys with value.

How do you iterate through a dictionary list?

In Python, to iterate the dictionary ( dict ) with a for loop, use keys() , values() , items() methods. You can also get a list of all keys and values in the dictionary with those methods and list() . Use the following dictionary as an example. You can iterate keys by using the dictionary object directly in a for loop.


1 Answers

Instead of using mydict, you should be using mydict.items() with enumerate as:

for i, (k, v) in enumerate(mydict.items()):     # your stuff 

Sample example:

mydict = {1: 'a', 2: 'b'} for i, (k, v) in enumerate(mydict.items()):     print("index: {}, key: {}, value: {}".format(i, k, v))  # which will print: # ----------------- # index: 0, key: 1, value: a # index: 1, key: 2, value: b 

Explanation:

  • enumerate() returns an iterator object which contains tuples in the format: [(index, list_element), ...]
  • dict.items() returns an iterator object (in Python 3.x. It returns list in Python 2.7) in the format: [(key, value), ...]
  • On combining together, enumerate(dict.items()) will return an iterator object containing tuples in the format: [(index, (key, value)), ...]
like image 159
Moinuddin Quadri Avatar answered Oct 07 '22 00:10

Moinuddin Quadri