Back when I used to work as a QA engineer and when I first got into Python (around 7 years ago), one of the key concepts I learned to use was dict()
in Python. You might wonder what is dict()
in Python and what are the main features of a dictionary in Python? Let’s discuss the answer to these questions in great detail below.
What Is dict() In Python?
In Python, the dict()
function is used to create a dictionary.
A dictionary is a collection of key-value pairs, where each key is associated with a value.
This function takes in a sequence of items and returns a dictionary with the items in the sequence as keys and values.
For example, you could use the dict()
function to create a dictionary like this:
my_dict = dict(
[
('key1', 'value1'),
('key2', 'value2')
]
)
This would create a dictionary with two key-value pairs: 'key1'
would be associated with 'value1'
, and 'key2'
would be associated with 'value2'
.
You can then access the values in the dictionary using the keys, like this:
print(my_dict['key1']) # Output: 'value1'
In addition to creating dictionaries using the dict()
function, you can also create them using curly braces {}
and specifying the key-value pairs directly, like this:
my_dict = {
'key1': 'value1',
'key2': 'value2'
}
This is generally considered to be a more concise and readable way to create dictionaries, so it is commonly used in Python programs.
This is a very basic answer to a What Is dict()
In Python? question. I’ll give you way more real Python project examples I’ve gathered over the years in the following sections of this post.
What Are The Main Features Of A Dictionary In Python?
The main features of dictionaries in Python are:
- Dictionaries are a collection of key-value pairs, where each key is associated with a value.
- Dictionaries are mutable, which means they can be changed after they are created.
- Dictionaries are unordered, which means that the items in a dictionary are not stored in a particular order.
- Dictionaries are optimized for retrieving values using the keys, so they are very efficient for looking up values based on a key.
- Dictionaries can be created using the
dict()
function or by using curly braces{}
and specifying the key-value pairs directly. - Dictionaries can be accessed, modified, and iterated over like other data types in Python.
Overall, dictionaries are a powerful and useful data type in Python, and they are used in a wide range of applications.
How Dictionaries In Python Are Mutable?
Here is an example of how dictionaries are mutable in Python:
# Create a dictionary with some initial key-value pairs
my_dict = {'key1': 'value1', 'key2': 'value2'}
# Print the dictionary
print(my_dict) # Output: {'key1': 'value1', 'key2': 'value2'}
# Add a new key-value pair to the dictionary
my_dict['key3'] = 'value3'
# Print the updated dictionary
print(my_dict) # Output: {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
# Update the value associated with an existing key
my_dict['key1'] = 'new_value1'
# Print the updated dictionary
print(my_dict) # Output: {'key1': 'new_value1', 'key2': 'value2', 'key3': 'value3'}
# Delete a key-value pair from the dictionary
del my_dict['key2']
# Print the updated dictionary
print(my_dict) # Output: {'key1': 'new_value1', 'key3': 'value3'}
In this example, we create a dictionary with some initial key-value pairs, and then we add a new key-value pair, update the value associated with an existing key, and delete a key-value pair from the dictionary.
As you can see, the dictionary is mutable and can be changed after it is created.
Is Python Dictionary Ordered Or Unordered?
In Python, dictionaries are unordered.
This means that the items in a dictionary are not stored in a particular order, and the order in which they are added to the dictionary may not be the same as the order in which they are retrieved.
For example, you could create a dictionary like this:
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
When you print the dictionary, the items may not be in the same order as they were added:
print(my_dict) # Output could be {'key2': 'value2', 'key1': 'value1', 'key3': 'value3'}
This is because dictionaries are unordered, so the order in which the items are stored is not fixed.
However, you can still access the values in the dictionary using the keys, like this:
print(my_dict['key1']) # Output: 'value1'
This is because the keys in a dictionary are unique and are used to identify the values in the dictionary, so you can always retrieve the correct value using the correct key, regardless of the order of the items in the dictionary.
Here is another example of how dictionaries are unordered in Python:
# Create a dictionary with some key-value pairs
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
# Print the dictionary
print(my_dict) # Output could be {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
# Create another dictionary with the same key-value pairs, but in a different order
my_dict_2 = {'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}
# Print the second dictionary
print(my_dict_2) # Output could be {'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}
# Compare the dictionaries
print(my_dict == my_dict_2) # Output: True
In this example, we create two dictionaries with the same key-value pairs, but in different orders.
When we print the dictionaries, you can see that the items in each dictionary are not stored in the same order.
However, when we compare the dictionaries using the ==
operator, we see that they are considered equal because they have the same key-value pairs, regardless of the order in which the items are stored.
This shows that dictionaries are unordered in Python.
How To Get A Specific Key Value From A Dictionary In Python?
Here are some examples of how dictionaries are optimized for retrieving values using the keys, and how they are very efficient for looking up values based on a key in Python:
# Create a dictionary with some key-value pairs
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
# Retrieve the value associated with a key using the square bracket notation
value = my_dict['key1']
print(value) # Output: 'value1'
# Check if a key exists in the dictionary
key_exists = 'key1' in my_dict
print(key_exists) # Output: True
# Use the get() method to retrieve the value associated with a key
value = my_dict.get('key1')
print(value) # Output: 'value1'
# Use the get() method to retrieve the value associated with a key, with a default value if the key does not exist
value = my_dict.get('key4', 'default_value')
print(value) # Output: 'default_value'
In these examples, you can see
- How you can use the square bracket notation to retrieve the value associated with a key in a dictionary
- How you can use the
in
operator to check if a key exists in a dictionary - How you can use the
get()
method to retrieve the value associated with a key
You can also see how the get()
method allows you to specify a default value to return if the key does not exist in the dictionary.
Having an option of using the default value might seem trivial, but it’s actually really useful when it comes to working with several conditions.
Instead of having a bunch of if statements I always suggest my students use get()
method.
If you want to know more about what students can learn in Python Mentoring, click here.
How To Search By Key In Python Dictionary?
Here’s a bit more advanced example of using Python dictionaries with a default value. Taken from a real project I’m currently working on.
The idea is to set different statement profiles based on the project brand.
We have dozens of clients and each client might require a slightly different statement profile.
Python dictionaries are prefect for such configuration:
default_statement_profile = {
'default_profile_setting_1': True,
'default_profile_setting_2': False,
}
brand_1_statement_profile = {
'feature_xyz': 'item_xyz'
}
brand_2_statement_profile = {
'feature_zyx': 'item_zyx'
}
CURRENT_BRAND = 'brand_1'
STATEMENT_PROFILE = {
'brand_1': brand_1_statement_profile,
'brand_2': brand_2_statement_profile,
'integration_tests': {
**default_statement_profile,
'show_processing_time': True,
'show_batch_id': True,
},
'brand_3': {
**default_statement_profile,
'show_currency_conversion': True,
'csv_use_decimal_comma': True,
'show_card_issuer': True,
'statement_limit': 100_000,
},
'brand_4': {
**default_statement_profile,
'show_card_issuer': True,
'overrides_acquirer': {
'payment_integration': 'payment_integration_name',
},
'overrides_payment_method': {
'payment_integration': 'payment_integration_name',
},
}
}.get(CURRENT_BRAND, default_statement_profile)
The default_statement_profile
dictionary contains the default settings that apply to all brands.
The brand_1_statement_profile
and brand_2_statement_profile
dictionaries contain settings that apply specifically to those brands.
Next, the code defines a constant called CURRENT_BRAND
that specifies which brand is currently being used.
This value is used to select the appropriate dictionary of settings for the current brand.
The STATEMENT_PROFILE
dictionary contains entries for each brand, where the key is the name of the brand and the value is the dictionary of settings for that brand.
STATEMENT_PROFILE = {...}
For some brands, the settings dictionary is created by merging the default settings with additional brand-specific settings using the **
(double-star) operator.
**default_statement_profile
This allows the brand-specific settings to override the default settings for those brands.
Finally, the get()
method is used to retrieve the dictionary of settings for the current brand.
.get(CURRENT_BRAND, default_statement_profile)
If the current brand is not found in the STATEMENT_PROFILE
dictionary, the default settings are used instead.
This allows the code to work with any brand, even if that brand is not explicitly defined in the STATEMENT_PROFILE
dictionary.
Leave a Reply
You must be logged in to post a comment.