Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Append Dictionary Keys and Values (In order ) in dictionary using Python
When you need to append dictionary keys and values in order, Python provides several approaches. The most straightforward method uses the list() function with .keys() and .values() methods to extract and concatenate them.
Basic Approach Using list() and Concatenation
This method converts dictionary keys and values to lists, then concatenates them ?
my_dict = {"January": 1, "Feb": 2, "March": 3, "April": 4, "May": 5, "June": 6}
print("The dictionary is:")
print(my_dict)
my_result = list(my_dict.keys()) + list(my_dict.values())
print("The ordered key and value are:")
print(my_result)
The dictionary is:
{'January': 1, 'Feb': 2, 'March': 3, 'April': 4, 'May': 5, 'June': 6}
The ordered key and value are:
['January', 'Feb', 'March', 'April', 'May', 'June', 1, 2, 3, 4, 5, 6]
Using List Comprehension
A more Pythonic approach using list comprehension ?
my_dict = {"January": 1, "Feb": 2, "March": 3, "April": 4, "May": 5, "June": 6}
result = [item for pair in zip(my_dict.keys(), my_dict.values()) for item in pair]
print("Interleaved keys and values:")
print(result)
Interleaved keys and values: ['January', 1, 'Feb', 2, 'March', 3, 'April', 4, 'May', 5, 'June', 6]
Using itertools.chain()
For memory-efficient concatenation of multiple iterables ?
import itertools
my_dict = {"January": 1, "Feb": 2, "March": 3, "April": 4, "May": 5, "June": 6}
result = list(itertools.chain(my_dict.keys(), my_dict.values()))
print("Chained keys and values:")
print(result)
Chained keys and values: ['January', 'Feb', 'March', 'April', 4, 'May', 5, 'June', 6]
Comparison
| Method | Memory Usage | Readability | Best For |
|---|---|---|---|
| List concatenation | Higher | High | Simple cases |
| List comprehension | Medium | Medium | Interleaved output |
| itertools.chain() | Lower | High | Large dictionaries |
How It Works
The
.keys()method returns a view object containing dictionary keysThe
.values()method returns a view object containing dictionary valuesConverting to
list()creates concrete lists from these view objectsThe
+operator concatenates the two lists in order
Conclusion
Use simple list concatenation for basic key-value appending. For memory efficiency with large dictionaries, consider itertools.chain(). List comprehension works well when you need interleaved key-value pairs.
