Iterate list of dictionaries Python | Example code

There are many ways to Iterate the list of dictionaries in Python. Some methods are using range with len function, Using while loop, List Comprehension, etc. the possibilities are endless, it’s your choice what you prefer.

Examples Iterate list of dictionaries in Python

Simple example code.

Iterate over the indices of the range of the len of the list:

Using range() and len() funcitons.

lst = [{'a': 1}, {'b': 3}, {'c': 5}]

for i in range(len(lst)):
    for key in lst[i]:
        print(lst[i][key])

Output:

Iterate list of dictionaries Python

Using while loop with an index counter:

lst = [{'a': 1}, {'b': 3}, {'c': 5}]

index = 0
while index < len(lst):
    for key in lst[index]:
        print(lst[index][key])
    index += 1

Output:

1
3
5

Iterate over the elements in the list directly

lst = [{'a': 1}, {'b': 3}, {'c': 5}]

for dic in lst:
    for key in dic:
        print(dic[key])

Output:

1
3
5

List Comprehension

Iterations inside a list-comprehension or a generator and unpack them later:

lst = [{'a': 1}, {'b': 3}, {'c': 5}]

res = [val for dic in lst for val in dic.values()]

print(res)

Output: [1, 3, 5]

Source: stackoverflow.com

Do comment if you have any doubts and suggestions on this Python List dictionary topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

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