Append Dictionary Keys and Values (In order) in Dictionary Python (original) (raw)
Last Updated : 13 Nov, 2025
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.
Python `
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.
Python `
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.
Python `
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.
Python `
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.