In this tutorial, we will explore how to get a single key-value pair from a dictionary in Python. A Python Dictionary is a collection of data that is unordered, changeable, and indexed.
Python dictionaries are written with curly brackets, and they have keys and values. If you want to extract a single key-value pair from a Python dictionary, you can achieve that using a couple of methods that this tutorial will cover.
Step 1: Creating a Dictionary
First, let’s create a simple Python dictionary with some key-value pairs. Remember, a Python dictionary is created by using the curly { } brackets enclosed with some key-value pairs. Look at the below code:
1 2 3 4 5 |
python_dictionary = { "Python": "A popular programming language", "Java": "Another popular programming language", "C++": "A high-performance language" } |
Step 2: Accessing a value using a key
You can get the value of a key by referencing the key inside square brackets []. Below is the code to get the value of the key “Python”.
1 2 |
value = python_dictionary["Python"] print(value) |
Output:
A popular programming language
Step 3: Using the get() method
Python also provides a built-in method called get() that returns the value for the given key if present in the dictionary.
1 2 |
value = python_dictionary.get("Python") print(value) |
Output:
A popular programming language
Full Code
1 2 3 4 5 6 7 8 9 10 11 |
python_dictionary = { "Python": "A popular programming language", "Java": "Another popular programming language", "C++": "A high-performance language" } value = python_dictionary["Python"] print(value) value = python_dictionary.get("Python") print(value) |
Conclusion
In this tutorial, we discussed how to extract a specific key-value pair from a Python dictionary. Starting by creating a dictionary, we moved on to access the value of a particular key by either using square brackets or employing the get() method.
Both methods are equally effective and easy to implement. To understand more about Python dictionaries, consider checking the official Python documentation.