Append Dictionary Keys and Values (In order ) in dictionary using Python


When it is required to append the keys and values of a dictionary in order, the ‘list’ method can be used. Along with this, the ‘.keys’ and ‘.values’ method can be used access the specific keys and values of the dictionary.

Below is a demonstration of the same −

Example

 Live Demo

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)

Output

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]

Explanation

  • A dictionary is defined, and is displayed on the console.

  • The keys of the dictionary are accessed using the ‘keys’ method and the values of dictionary are accessed using ‘values’ method.

  • It is converted to a list and is concatenated using the ‘+’ operator.

  • This is displayed on the console as the output.

Updated on: 14-Apr-2021

581 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements