Given two lists one containing dictionary keys and the other containing corresponding values create a dictionary that preserves the order of keys as they appear. For Example:
Input: keys = ["name", "age", "city"], values = ["Harry", 30, "New York"]
Output: {'name': 'Harry', 'age': 30, 'city': 'New York'}
Below are methods to create an ordered dictionary:
Using zip and Dictionary Constructor
This method pairs keys and values using zip and converts them into a dictionary in a single step.
keys = ["name", "age", "city"]
values = ["Robin", 30, "New York"]
d = dict(zip(keys, values))
print(d)
Output
{'name': 'Robin', 'age': 30, 'city': 'New York'}
Explanation:
- zip(keys, values): Pairs keys with their corresponding values.
- dict(): Creates the dictionary in insertion order.
Using for Loop with Direct Assignment
This method involves manually iterating over the keys and values to append them in order.
keys = ["name", "age", "city"]
values = ["Robin", 30, "New York"]
d = {}
for k, v in zip(keys, values):
d[k] = v
print(d)
Output
{'name': 'Robin', 'age': 30, 'city': 'New York'}
Explanation:
- zip(keys, values): Combines keys and values for iteration.
- Each key-value pair is appended to the dictionary using assignment.
Using update() with Dictionary Comprehension
This method uses a dictionary comprehension to create key-value pairs and appends them to an existing dictionary using the update method.
keys = ["name", "age", "city"]
values = ["Robin", 30, "New York"]
d = {}
d.update({k: v for k, v in zip(keys, values)})
print(d)
Output
{'name': 'Robin', 'age': 30, 'city': 'New York'}
Explanation:
- {k: v for k, v in zip(keys, values)}: Generates a dictionary from paired keys and values.
- d.update(...): Adds all pairs to dictionary d.
Using OrderedDict from collections
This method uses OrderedDict to create a dictionary that preserves the insertion order of keys, which is especially useful for Python versions earlier than 3.7.
from collections import OrderedDict
keys = ["name", "age", "city"]
values = ["Robin", 30, "New York"]
d = OrderedDict(zip(keys, values))
print(d)
Output
OrderedDict({'name': 'Robin', 'age': 30, 'city': 'New York'})
Explanation: OrderedDict(zip(keys, values)) creates an ordered dictionary preserving the order of keys.