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: 2021-04-14T12:40:34+05:30

796 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements