Last Updated : 15 Jul, 2025
Appending dictionary keys and values in order ensures that the sequence in which they are added is preserved. For example, when working with separate lists of keys and values, we might want to append them in a specific order to build a coherent dictionary. Let's explore several methods to achieve this.
Using zip and Dictionary ConstructorThis is the most efficient and commonly used method to append keys and values in order.
Python
# Initialize lists of keys and values
keys = ["name", "age", "city"]
values = ["Alice", 30, "New York"]
# Create a dictionary by zipping keys and values
d = dict(zip(keys, values))
# Print the dictionary
print(d)
{'name': 'Alice', 'age': 30, 'city': 'New York'}
Explanation:
This method involves manually iterating over the keys and values to append them in order.
Python
# Initialize lists of keys and values
keys = ["name", "age", "city"]
values = ["Alice", 30, "New York"]
# Initialize an empty dictionary
d = {}
# Append keys and values in order
for k, v in zip(keys, values):
d[k] = v
# Print the dictionary
print(d)
{'name': 'Alice', 'age': 30, 'city': 'New York'}
Explanation:
This method uses a dictionary comprehension to create key-value pairs and appends them to an existing dictionary using the update method.
Python
# Initialize lists of keys and values
keys = ["name", "age", "city"]
values = ["Alice", 30, "New York"]
# Initialize an empty dictionary
d = {}
# Append keys and values using dictionary comprehension and update
d.update({k: v for k, v in zip(keys, values)})
# Print the dictionary
print(d)
{'name': 'Alice', 'age': 30, 'city': 'New York'}
Explanation:
This method is useful if maintaining the order is critical, especially when working with Python versions prior to 3.7.
Python
from collections import OrderedDict
# Initialize lists of keys and values
keys = ["name", "age", "city"]
values = ["Alice", 30, "New York"]
# Create an OrderedDict by zipping keys and values
d = OrderedDict(zip(keys, values))
# Print the dictionary
print(d)
OrderedDict({'name': 'Alice', 'age': 30, 'city': 'New York'})
Explanation:
This method creates a list of tuples representing key-value pairs and converts it to a dictionary.
Python
# Initialize lists of keys and values
keys = ["name", "age", "city"]
values = ["Alice", 30, "New York"]
# Create a dictionary using a list of tuples
d = dict([(k, v) for k, v in zip(keys, values)])
# Print the dictionary
print(d)
{'name': 'Alice', 'age': 30, 'city': 'New York'}
Explanation:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4