List of dictionaries Python | Example code

A list of dictionaries simply means a list that contains multiple dictionaries. In python, it can easily create it.

[{'a': 1, 'b': 10}, {'c': 2, 'd': 20}, {'d': 3, 'e': 30}]

Example List of dictionaries Python

Simple example code. As you know list represent with square brackets [ ] and the dictionary with curly brackets { } in Python.

list_dict = [
    {
        'foo': 12,
        'bar': 14
    },
    {
        'moo': 52,
        'car': 641
    },
    {
        'doo': 6,
        'tar': 84
    }
]

print(list_dict)

Output:

List of dictionaries Python

Access List of Dictionaries

Dictionary is like any item in a list and list using an index method to access times. And to access a specific key: the value of the dictionary uses the key method.

list_dict = [
    {
        'foo': 12,
        'bar': 14
    },
    {
        'moo': 52,
        'car': 641
    },
    {
        'doo': 6,
        'tar': 84
    }
]
# Single
print(list_dict[0])
print(list_dict[0]['bar'])

Output:

{‘foo’: 12, ‘bar’: 14}
14

Update Dictionary in List of Dictionaries

First get element by using index value in the square bracket and then use key-value to update dictionary element.

list_dict = [
    {
        'foo': 12,
        'bar': 14
    },
    {
        'moo': 52,
        'car': 641
    },
    {
        'doo': 6,
        'tar': 84
    }
]
# Update value
list_dict[0]['bar'] = 100

# Add a new dictionary
list_dict[1]['Yoo'] = 99

# Delete a dictionary
del list_dict[2]['doo']

print(list_dict)

Output: [{‘foo’: 12, ‘bar’: 100}, {‘moo’: 52, ‘car’: 641, ‘Yoo’: 99}, {‘tar’: 84}]

Append a Dictionary to List of Dictionaries

Use the append() method to add a new dict. It will add to the last of the list.

Using append

list_dict = [
    {
        'foo': 12,
        'bar': 14
    },
    {
        'moo': 52,
        'car': 641
    },
    {
        'doo': 6,
        'tar': 84
    }
]

list_dict.append({'A': 100, 'B': 200})

print(list_dict)

Output:

[{‘foo’: 12, ‘bar’: 14}, {‘moo’: 52, ‘car’: 641}, {‘doo’: 6, ‘tar’: 84}, {‘A’: 100, ‘B’: 200}]

Do comment if you have any doubts and suggestions on this Python list dictionary tutorial.

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.