Get both key and value from a dictionary using items() method
In this tutorial, you will learn how to get both key and value from a dictionary using items() method in Python
Basically, a dictionary is a data structure that stores the data in the form of key-value pairs. A dictionary can be declared by placing the key-value pairs in {} brackets, separated by commas, and methods like pop(), update(), popitem(), keys(), values(), get(), etc. are used to perform various operations on them.
In Python, there are several methods for obtaining key-value pairs from a dictionary, but here we will look at an easy one that uses the “items()” method. To get both key and value from a dictionary using items() method,
Here’s a step-by-step technique to perform this:
Initializing a dictionary
Initialize a dictionary with keys and their corresponding values.
origin = {"Python": "Netherlands", "JavaScript": "USA", "PHP": "Canada"}
Iterating over the dictionary
Here, we have to use a for loop to obtain each key-value pair as it iterates over the given dictionary by using the items() method.
print("Dictionary's key-value pairs are: ") for key, value in origin.items(): print(key, value)
Both key and value pairs are printed after each iteration, where the key is assigned to the variable ‘key’ and the value to the variable ‘value’.
Complete Code
origin = {"Python": "Netherlands", "JavaScript": "USA", "PHP": "Canada"} print("The primary dictionary is: \n" + str(origin)) print("The dictionary's key-value pairs are: ") for key, value in origin.items(): print(key, value)
The print statements are optional and only included for better understanding.
The dictionary is converted into its string form using the str() function and is concatenated to the existing string “The primary dictionary is: ” using the ‘+’ symbol.
Output
The primary dictionary is: {'Python': 'Netherlands', 'JavaScript': 'USA', 'PHP': 'Canada'} The dictionary's key-value pairs are: Python Netherlands JavaScript USA PHP Canada
We can get both the key and value from any dictionary using this straightforward approach.
Here’s one more example to help you better understand the concept.
salaries = {"Anthony": 40000, "Colin": 60000, "Henry": 80000} print("Key-value pairs of the example dictionary are: ") for key, value in salaries.items(): print(key, value)
Additionally, you may also refer to:
Leave a Reply