Python Dictionaries
Python dictionaries are a built-in data type that allow you to store and retrieve key-value pairs. A dictionary is defined using curly braces {} and each key-value pair is separated by a colon :. The key and the value can be of any data type, such as integers, floats, strings, or even other dictionaries.
Dictionaries have several methods for working with them, such as .keys() to retrieve a list of keys, .values() to retrieve a list of values, and .items() to retrieve a list of key-value pairs as tuples. Dictionaries can also be iterated over using a for loop.
Overall, dictionaries are a powerful tool in Python for storing and accessing data in a flexible and efficient way.
Syntax of python dictionary:
my_dict = {key1: value1, key2: value2, key3: value3}
where my_dict is the name of the dictionary, key1, key2, and key3 are the keys, and value1, value2, and value3 are the corresponding values.
The keys in a dictionary must be unique and can be of any immutable data type such as strings, integers, or tuples. The values in a dictionary can be of any data type, including other dictionaries.
Some of the key properties of Python dictionaries are:
Unordered: Unlike lists, dictionaries are unordered, meaning the order of the key-value pairs is not guaranteed to be the same as when they were created.
Mutable: Dictionaries are mutable, meaning you can add, delete, or modify key-value pairs after the dictionary has been created.
Dynamic: Dictionaries can grow or shrink dynamically as key-value pairs are added or removed.
Keys must be unique and immutable: Keys in a dictionary must be unique and immutable (cannot be changed), but values can be of any data type, including other dictionaries.
Efficient for lookups: Dictionaries are optimized for fast lookups of values based on keys, which makes them a great choice for storing and retrieving data that is organized by a unique identifier.
Keys are not sorted: Dictionaries do not maintain any sort of order for the keys, so you cannot access them by index. Instead, you must access them by key.
No duplicates allowed for keys: Dictionaries cannot have duplicate keys. If you try to add a key that already exists, it will overwrite the existing value for that key.
Overall, Python dictionaries are a powerful and flexible data structure that can be used for a wide range of applications, from storing configuration settings to building complex data structures for data analysis and machine learning.
my_dict = {‘apple’: 1, ‘orange’: 2, ‘banana’: 3}
print(my_dict)
Output: {‘apple’: 1, ‘orange’: 2, ‘banana’: 3}
Note that the order of the keys in the printed dictionary may be different from the order in which they were added.
my_dict = {‘apple’: 1, ‘orange’: 2, ‘banana’: 3}
my_dict[‘pear’] = 4
print(my_dict)
Output:{‘apple’: 1, ‘orange’: 2, ‘banana’: 3, ‘pear’: 4}
We added a new key-value pair to the dictionary.
my_dict = {‘apple’: 1, ‘orange’: 2, ‘banana’: 3}
del my_dict[‘orange’]
print(my_dict)
We removed a key-value pair from the dictionary.
my_dict = {‘apple’: 1, ‘orange’: 2, ‘banana’: 3}
my_dict[(‘grape’, ‘red’)] = 4
print(my_dict)
Output:{‘apple’: 1, ‘orange’: 2, ‘banana’: 3, (‘grape’, ‘red’): 4}
We added a new key-value pair with a tuple key, which is immutable.
my_dict = {‘apple’: 1, ‘orange’: 2, ‘banana’: 3}
print(my_dict[‘orange’])
Output:2
We looked up the value associated with the ‘orange’ key.
my_dict = {‘apple’: 1, ‘orange’: 2, ‘banana’: 3}
for key in my_dict:
print(key)
Output:
apple
orange
banana
Note that the keys are printed in a different order than they were added to the dictionary.
my_dict = {‘apple’: 1, ‘orange’: 2, ‘banana’: 3}
my_dict[‘banana’] = 4
print(my_dict)
Output:{‘apple’: 1, ‘orange’: 2, ‘banana’: 4}
We changed the value associated with the ‘banana’ key.
my_dict = {‘apple’: 1, ‘orange’: 2, ‘banana’: 3}
for key in my_dict:
print(key)
Output:
apple
orange
banana
Note that the keys are printed in a different order than they were added to the dictionary.
my_dict = {‘apple’: 1, ‘orange’: 2, ‘banana’: 3}
my_dict[‘apple’] = 4
print(my_dict)
Output:{‘apple’: 4, ‘orange’: 2, ‘banana’: 3}
We modified the value associated with the ‘apple’ key.
my_dict = {‘apple’: 1, ‘orange’: 2, ‘banana’: 3}
my_dict[‘pear’] = 4
print(my_dict)
Output:{‘apple’: 1, ‘orange’: 2, ‘banana’: 3, ‘pear’: 4}
We added a new key-value pair to the dictionary.
my_dict = {‘apple’: 1, ‘orange’: 2, ‘banana’: 3}
my_dict[(1, 2)] = ‘tuple_key’
print(my_dict)
Output:
{‘apple’: 1, ‘orange’: 2, ‘banana’: 3, (1, 2): ‘tuple_key’}
We added a new key-value pair with a tuple key, which is immutable.
my_dict = {‘apple’: 1, ‘orange’: 2, ‘banana’: 3}
if ‘apple’ in my_dict:
print(my_dict[‘apple’])
Output:1
We checked if the key ‘apple’ is in the dictionary and then looked up its value.
my_dict = {‘apple’: 1, ‘orange’: 2, ‘banana’: 3}
print(list(my_dict.keys()))
Output: [‘apple’, ‘orange’, ‘banana’]
We converted the keys of the dictionary to a list, which is printed in the order they were added to the dictionary.
my_dict = {‘apple’: 1, ‘orange’: 2, ‘banana’: 3}
my_dict[‘banana’] = 4
print(my_dict)
Output:{‘apple’: 1, ‘orange’: 2, ‘banana’: 4}
We changed the value associated with the ‘banana’ key. Note that the key is not duplicated, but its value is updated.
Python dictionaries have many uses and are a fundamental data structure in Python. Here are some examples of their common uses:
The most common use case for dictionaries is storing key-value pairs. For example:
customer = {‘name’: ‘Alice’, ’email’: ‘alice@example.com’, ‘phone’: ‘123-456-7890’}
customer = {‘name’: ‘Alice’, ’email’: ‘alice@example.com’, ‘phone’: ‘123-456-7890’}
Here, the dictionary stores the customer’s name, email, and phone number, with the keys being ‘name’, ’email’, and ‘phone’, respectively. This makes it easy to access and manipulate the data.
Dictionaries are also useful for counting the occurrences of items in a list or string. For example:
my_list = [‘apple’, ‘banana’, ‘orange’, ‘banana’, ‘apple’, ‘orange’, ‘orange’]
count_dict = {}
for item in my_list:
if item in count_dict:
count_dict[item] += 1
else:
count_dict[item] = 1
print(count_dict)
Output:{‘apple’: 2, ‘banana’: 2, ‘orange’: 3}
Here, we iterate over the list and use a dictionary to count the number of occurrences of each item.
Dictionaries are also useful for storing configuration settings for an application. For example:
config = {‘db_host’: ‘localhost’, ‘db_port’: 5432, ‘db_user’: ‘myuser’, ‘db_pass’: ‘mypassword’}
Here, the dictionary stores the database connection settings for an application.
Dictionaries can be used for caching results to avoid recalculating expensive computations. For example:
def fib(n, cache={}):
if n in cache:
return cache[n]
if n < 2:
return n
result = fib(n-1) + fib(n-2)
cache[n] = result
return result
Here, we define a recursive function to calculate the Fibonacci sequence, but we use a dictionary as a cache to store the results of previous computations. This makes subsequent calculations much faster.
Dictionaries can be used to group data by a key. For example:
students = [ {‘name’: ‘Alice’, ‘grade’: ‘A’}, {‘name’: ‘Bob’, ‘grade’: ‘B’}, {‘name’: ‘Charlie’, ‘grade’: ‘A’}, {‘name’: ‘David’, ‘grade’: ‘C’}, {‘name’: ‘Eve’, ‘grade’: ‘B’}]
grades = {}
for student in students:
if student[‘grade’] in grades:
grades[student[‘grade’]].append(student[‘name’])
else:
grades[student[‘grade’]] = [student[‘name’]]
print(grades)
Output:
{‘A’: [‘Alice’, ‘Charlie’], ‘B’: [‘Bob’, ‘Eve’], ‘C’: [‘David’]}
Here, we use a dictionary to group the students by their grade. Each grade is a key in the dictionary, and the value is a list of student names.
Dictionaries can be used to map functions to values. For example:
def add(a, b):
return a + b
def subtract(a, b):
return a – b
operations = {
‘add’: add,
‘subtract’: subtract
}
result = operations[‘add’](3, 4)
print(result)
Output:7
Here, we define two functions, ‘add’ and ‘subtract’, and store them in a dictionary. We can then use the dictionary to call the appropriate function based on a key.
Dictionaries can be used to enumerate values. For example:
colors = {
‘red’: 1,
‘green’: 2,
‘blue’: 3
}
for i, color in enumerate(colors):
print(i, color)
Output:
Here, we use the ‘enumerate’ function to loop over the dictionary and assign an index to each value.
Dictionaries can be used to create lookup tables. For example:
lookup = {
‘A’: ‘Adenine’,
‘C’: ‘Cytosine’,
‘G’: ‘Guanine’,
‘T’: ‘Thymine’
}
Here, we create a lookup table to map DNA nucleotides to their full names.
Dictionaries can be used to convert data from one format to another. For example:
data = {
‘name’: ‘Alice’,
‘age’: 30,
’email’: ‘alice@example.com’
}
csv_data = ‘,’.join([str(data[key]) for key in data])
print(csv_data)
Output: Alice,30,alice@example.com
Here, we convert a dictionary to a comma-separated value (CSV) format.
Dictionaries can be used to create custom objects with dynamic properties. For example:
class CustomObject:
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
data = {‘name’: ‘Alice’, ‘age’: 30}
obj = CustomObject(**data)
print(obj.name)
print(obj.age)
Output:
Alice
30
Here, we define a custom object with dynamic properties based on a dictionary. We can then access the properties using dot notation.
Dictionaries can be used to store configuration settings for an application. For example:
config = {
‘server’: ‘localhost’,
‘port’: 8080,
‘debug’: True
}
Here, we store configuration settings for a web server.
Dictionaries can be used to group data by a specific attribute. For example:
students = [ {‘name’: ‘Alice’, ‘grade’: ‘A’}, {‘name’: ‘Bob’, ‘grade’: ‘B’}, {‘name’: ‘Charlie’, ‘grade’: ‘C’}]
grades = {}
for student in students:
if student[‘grade’] not in grades:
grades[student[‘grade’]] = []
grades[student[‘grade’]].append(student[‘name’])
print(grades)
Output:{‘A’: [‘Alice’], ‘B’: [‘Bob’], ‘C’: [‘Charlie’]}
Here, we group students by their grades and store the result in a dictionary.
Dictionaries can be used to create sparse matrices. For example:
matrix = {
(0, 1): 2,
(2, 0): 3,
(2, 1): 1
}
Here, we create a sparse matrix with only a few non-zero elements.
Dictionaries can be used to implement caches for expensive computations. For example:
def fibonacci(n, cache={}):
if n in cache:
return cache[n]
if n < 2:
return n
result = fibonacci(n-1) + fibonacci(n-2)
cache[n] = result
return result
print(fibonacci(10))
Output:55
Here, we implement a cache for the Fibonacci sequence function to avoid recomputing values that have already been computed.
Dictionaries can be used to implement counters for elements in a list or string. For example:
from collections import defaultdict
text = ‘hello world’
counter = defaultdict(int)
for char in text:
counter[char] += 1
print(counter)
Output:
defaultdict(<class ‘int’>, {‘h’: 1, ‘e’: 1, ‘l’: 3, ‘o’: 2, ‘ ‘: 1, ‘w’: 1, ‘r’: 1, ‘d’: 1})
Here, we count the occurrences of each character in a string and store the result in a dictionary using a defaultdict.