5 Gems About Python Dictionaries You Really Should Know

Hey there, my name is Blake Downward from Australia. Background in e-commerce, finance and economics - now making the move to Data Science and applied Machine Learning.
Dictionaries are a fundamental data structure that every Python developer will encounter at some point. They offer an efficient way to store and manipulate data, making them a go-to structure for many programming tasks. In this article, we'll explore five handy ways to use dictionaries and improve your workflows.
Tip 1: Zip Lists of Keys and Values to a Dictionary
One of the simplest ways to create a dictionary in Python is by using the zip function to combine lists of keys and values. Take the following for example:
keys = ['name', 'age', 'gender']
values_1 = ['Alice', 30, 'female']
values_2 = ['Bob', 40, 'male']
my_dict_1 = dict(zip(keys, values_1))
print(my_dict_1) # Output: {'name': 'Alice', 'age': 30, 'gender': 'female'}
my_dict_2 = dict(zip(keys, values_2))
print(my_dict_2) # Output: {'name': 'Bob', 'age': 40, 'gender': 'male'}
Tip 2: Enumerate a List of Values
When you have a list of values and want to convert it into a dictionary with enumerated keys, use Python's enumerate function. This is useful when you need to associate each value with a unique identifier. Here's a simple example:
values = ['apple', 'banana', 'cherry']
my_dict = {idx: value for idx, value in enumerate(values)}
print(my_dict) # Output: {0: 'apple', 1: 'banana', 2: 'cherry'}
Tip 3: Storing kwargs for Unpacking to Python Functions
Python allows you to store keyword arguments (kwargs) in a dictionary and then unpack them when calling a function. This technique is particularly useful for simplifying function calls with multiple arguments. Here's how it works:
def my_function(name, age):
print(f"Name: {name}, Age: {age}")
kwargs = {'name': 'John', 'age': 25}
my_function(**kwargs) # Output: Name: John, Age: 25
Take note of the double asterisk (**) before "kwargs" in the function call. this is an important instruction to the function which says "unpack the kwargs dictionary (key/value pairs) as parameters for this function".
Tip 4: Using a Dictionary for Logic Instead of if/else Statements
Dictionaries can serve as efficient lookup tables, replacing clunky if/else statements in certain scenarios. This approach enhances readability and maintainability of your code. Here's an example of using conditional statements:
def apply_discount(total, customer_type=None):
if customer_type == 'premium':
return (1-0.1)*total
elif customer_type == 'vip':
return (1-0.2)*total
else:
return total
print(apply_discount(10, 'vip')) # Output: 8
print(apply_discount(10, 'guest')) # Output: 10 (default discount for unknown type)
And here's an example of using key-value pairs to take care of the conditional logic. This is just a small example, but you can see how this can save a lot of headache as the number of conditionals grows.
def apply_discount(total, customer_type=None):
discount_rates = {'premium': 0.1, 'vip': 0.2}
return total * (1 - discount_rates.get(customer_type, 0.0)
print(apply_discount(10, 'vip')) # Output: 8
print(apply_discount(10, 'guest')) # Output: 10 (default discount for unknown type)
Tip 5: Return a List of Dictionary Keys or Values
When using dictionaries, sometimes it's useful to return just a list of "keys", or just a list of "values". This is basically the opposite of the "zip" example above. For example...
daily_sales = {'bananas': 32.61, 'apples': 49.12, 'oranges': 9.37}
products = list(daily_sales.keys())
print(products) # outputs ['bananas', 'apples', 'oranges]
revenues = list(daily_sales.values())
print(revenues) # outputs [32.61, 49.12, 9.37]
Conclusion:
Dictionaries are a fundamental data structure for Python developers. Not only are they useful for managing data within Python scripts, but they are readily serialised to framework agnostic data structures such as; JSON, YAML, TOML and XML. These five tips are just the tip of the iceberg for using dictionaries in Python effectively. What are your favourite things to do with Python dictionaries? Drop it in the comments below!
Additional Resources:


