Python is a powerful and versatile programming language that makes it easy to work with various data structures, such as dictionaries. In this tutorial, we will discuss what a dictionary is and how to query a dictionary in Python.
What is a Dictionary in Python?
A dictionary is an unordered collection of key-value pairs, where each key is unique. Dictionaries can be used for a wide variety of purposes, such as counting word frequencies, storing configuration settings, or representing a graph as an adjacency list. In Python, dictionaries are created using the dict keyword or curly braces {}.
Creating a Dictionary
Let’s create a simple dictionary that represents the number of fruits in a basket:
fruits = { "apples": 4, "bananas": 6, "oranges": 2 }
Querying a Dictionary
There are several methods to query a dictionary in Python, which we will discuss in the following sections:
1. Using Square Bracket Notation
You can access the value associated with a specific key using square bracket notation. For example, to get the number of apples in the basket:
apples = fruits["apples"] print(apples) # Output: 4
Note that if the key does not exist in the dictionary, a KeyError will be raised. To avoid this, you can use the in keyword to check if a key is in the dictionary:
if "apples" in fruits: apples = fruits["apples"] print(apples)
2. Using the get() Method
Another way to query a dictionary is by using the get() method, which returns the value associated with a key if it exists, or a default value otherwise:
apples = fruits.get("apples", 0) print(apples) # Output: 4
3. Using the items() Method
The items() method returns a view object displaying a list of the dictionary’s key-value pairs. You can use this method to loop through the keys and values in the dictionary:
for key, value in fruits.items(): print(key, value)
Output:
apples 4 bananas 6 oranges 2
Conclusion
In this tutorial, we have discussed what a dictionary is and how to query a dictionary in Python using various methods. By understanding these concepts, you can effectively work with dictionaries in your Python projects.