Today's featured video:



Python Programming Tutorial - Adding Dictionaries to Lists

Dictionaries are an important data structure in Python. They hold key-value pairs, and can be used as elements within lists or arrays, providing a powerful way of structuring complex data. This tutori …

Updated November 28, 2023

Dictionaries are an important data structure in Python. They hold key-value pairs, and can be used as elements within lists or arrays, providing a powerful way of structuring complex data. This tutorial will show you how to add dictionaries to a list using Python programming language.

  1. Creating a List with Dictionaries: In Python, we can use curly braces {} for defining the dictionary and square brackets [] for creating lists and tuples.
# Define a Dictionary
my_dict = {'name': 'John', 'age': 30}

# Create an empty list
my_list = []

# Adding dictionary to the list
my_list.append(my_dict)

print(my_list) # Output: [{'name': 'John', 'age': 30}]
  1. Accessing Dictionary Values in a List: Dictionaries within lists can be accessed just like any other data structure in Python.
# Accessing values from the dictionary
print(my_list[0]['name']) # Output: John
print(my_list[0]['age'])  # Output: 30
  1. Multiple Dictionaries in a List: We can add multiple dictionaries to our list and access the values of each dictionary separately.
# Define another dictionary
another_dict = {'city': 'New York', 'job': 'Software Developer'}

# Add both dictionaries to the list
my_list.append(another_dict)

print(my_list) # Output: [{'name': 'John', 'age': 30}, {'city': 'New York', 'job': 'Software Developer'}]
  1. Dictionary within a List: A dictionary can also be a member of another list, in which case it behaves like any other data type, such as an integer or string.
# Create another list with integers and strings
another_list = ['Hello', 123, {'name': 'Sam'}]
print(another_list) # Output: ['Hello', 123, {'name': 'Sam'}]
  1. Iteration: We can loop through each dictionary in the list and access their values as shown below.
for item in my_list:
    if isinstance(item, dict):
        for key, value in item.items():
            print(f'{key}: {value}')

This tutorial gives a clear overview of how to add dictionaries to a list in Python, and provides examples on how to access values from the dictionary inside the list.