Skip to content

Iterate list of dictionaries Python | Example code

  • by

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.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading