Dictionaries in Python

Dictionaries in Python are collections of data pairs, which are mutable, unordered, and indexed. While other compound data types such as lists and tuples have only value as an element, a dictionary has key-value pairs. This key-value feature makes it more efficient for looking up things.

You can create a dictionary in Python as shown below:

student_dict = {
"name" : "John",
"age" : 20,
"courses" : ["Math", "Computing"]
}

Here, name, age, courses are the keys and John, 20, ['Math', 'Computing'] are the corresponding values. The values can be of any type and can also be changed, but the key must always be of an immutable type (string, number or tuple).

Why Use Dictionaries?

Dictionaries in Python are used for their high speed and ability to link pieces of related information. The keys help access, manipulate, or alter data directly without having to know the index position. They are highly optimized for retrieving data, provided we know the key to look up.

The benefits and use-cases of dictionaries include:

  • Database-like functionality: Since dictionaries in Python are used to store `key-value pairs, they can be used to represent structured data in a database.
employee = {
"name" : "Kim",
"role" : "Data Scientist",
"id" : 007
}
  • Easy data retrieval: With the key, you can access its associated value in constant time, which is not possible in other data types.
print(employee["name"])
# Output: Kim
  • Flexibility: Keys in the dictionary can be of different types, and so can be their associated values. This means one dictionary can hold many different types of data, offering flexibility.
random_dict = {
1: "one",
"two": 2,
(1,2): "tuple"
}

Syntax

Dictionary is a mutable unordered collection of elements in Python that stores data values in key-value pairs. The dictionary is versatile in Python because it allows users to access values very quickly.

Dictionary Initialization:

A dictionary can be created by placing a comma-separated list of key-value pairs within the curly braces {}.

# Create an empty dictionary

dict_empty = {}
print(dict_empty)  # Prints {}

# Dictionary with integer keys
dict_int = {1: 'apple', 2: 'banana'}
print(dict_int)  # Prints {1: 'apple', 2: 'banana'}

# Dictionary with string keys
dict_str = {'name': 'John', 'age': 22}
print(dict_str)  # Prints {'name': 'John', 'age': 22}

# Using dict()
dict_using_dict = dict({1: 'apple', 2: 'banana'})
print(dict_using_dict)  # Prints {1: 'apple', 2: 'banana'}

Adding New Elements:

Adding elements to the dictionary can be done either through the update() function or by using the key.

data = {1: 'apple', 2: 'banana'}

# Adding key-value pair using key
data[3] = 'mango'
print(data)  # Prints {1: 'apple', 2: 'banana', 3: 'mango'}

# Adding key-value pair using update()
data.update({4: 'grapes'})
print(data)  # Prints {1: 'apple', 2: 'banana', 3: 'mango', 4: 'grapes'}

Initializing with Default Values:

To initialize a dictionary with default values, use the defaultdict function from the collections module. The defaultdict function automatically assigns a default value to a nonexistent key.

from collections import defaultdict

# Initialize dictionary with default integer value
data_int = defaultdict(int)
print(data_int[1])  # Prints 0

# Initialize dictionary with default list value
data_list = defaultdict(list)
print(data_list[1])  # Prints []

# Initialize dictionary with default string value
data_str = defaultdict(str)
print(data_str[1])  # Prints ' '

In the above examples, accessing a non-existent key does not result in a KeyError but instead returns the default value. For the integer and string, this default value is 0 and an empty string, respectively, and for the list, it defaults to an empty list ([]).

With defaultdict, one can initialize a dictionary with default values. This makes dictionaries a very flexible data structure in Python, providing efficient ways to organize and access data.

Key Access in Python Dictionaries:

Python provides the simplest way to access dictionary values–by using their keys. They are also known as direct key access.

# define a dictionary
dict = {'name': 'John', 'age': 21, 'profession': 'Engineer'}

# access elements using keys
print(dict['name'])  # Output: John
print(dict['age'])  # Output: 21

By specifying the key in square brackets close to the dictionary’s name, we retrieve their associated values. If we call a key that does not exist in the dictionary, a KeyError will occur.

Get Method for Accessing Elements

The get() method is another method for retrieving values. Unlike direct key access, if the key does not exist, the get() method does not raise an error but returns None.

For example:

# define a dictionary
dict = {'name': 'John', 'age': 21, 'profession': 'Engineer'}

# access elements using get() method
print(dict.get('name'))  # Output: John
print(dict.get('address'))  # Output: None

You can also provide a default value to return if the key does not exist. For example:

# accessing a non-existing key with default value
print(dict.get('address', 'Not Available'))  # Output: Not Available

Keys and Values Methods:

The keys() and values() methods in Python dictionaries return the lists of all keys and values respectively in the dictionary.

For example:

# define a dictionary
dict = {'name': 'John', 'age': 21, 'profession': 'Engineer'}

# get all keys
print(dict.keys())  # Output: dict_keys(['name', 'age', 'profession'])

# get all values
print(dict.values())  # Output: dict_values(['John', 21, 'Engineer'])

If you need access to both keys and values, you can use the items() method.

# get all keys-values pairs
print(dict.items())  # Output: dict_items([('name', 'John'), ('age', 21), ('profession', 'Engineer')])

These provide an easy way to loop through the dictionary or return its contents without hardcoding the specific keys.

Updating Values in a Dictionary

To modify or update a dictionary value, you simply access the dictionary key and assign it a new value.

Here’s a simple dictionary we’ll use for examples:

ages = { 'John': 25, 'Mary': 29, 'Andre': 36 }

Let’s say we want to update John’s age to 26. Here’s how to do it:

ages['John'] = 26    # update existing entry
print(ages)          # {'John': 26, 'Mary': 29, 'Andre': 36}

The same approach works if you want to add a new entry to the dictionary:

ages['Amy'] = 22     # Add new entry
print(ages)          # {'John': 26, 'Mary': 29, 'Andre': 36, 'Amy': 22}

Removing Elements from Dictionary

To remove a value from a dictionary, you can use Python’s del statement. Let’s remove John from our dictionary:

del ages['John']     # remove entry with key 'John'
print(ages)          # {'Mary': 29, 'Andr': 36, 'Amy': 22}

If you try to delete a key that isn’t in the dictionary, Python will raise a KeyError. To avoid this, use the dict.pop() method, which removes the key if it exists but does nothing if it doesn’t:

ages.pop('Jane', None) 

The above code removes Jane if she exists in the dictionary. However, no keyerror is thrown if she does not exist.

Clearing The Dictionary

If you want to remove all elements from the dictionary, making it empty, Python provides a dictionary method called clear(). For example:

ages.clear()         # remove all entries in dictionary
print(ages)          # {}

Advanced Dictionary Methods

Let’s look into some crucial dictionary methods, like Pop, Items, Update, the Len function and a few more.

POP Method

The pop method in a Python dictionary is used to remove a specific key-value pair. The syntax is:

dictionary.pop(key)

Where key is the key you wish to remove. For example:

userInfo = {
'name': 'John',
'age': '24',
'location': 'USA'
}

userInfo.pop('age')
print(userInfo)

The output of the above code would be: {'name': 'John', 'location': 'USA'}

ITEMS Method

The items method returns a view object that displays a list of a dictionary’s key-value tuple pairs. The syntax is:

dictionary.items()

For example:

userInfo = {
'name': 'John',
'age': '24',
'location': 'USA'
}

print(userInfo.items())

The output will be: dict_items([('name', 'John'), ('age', '24'), ('location', 'USA')])

UPDATE Method

Python dictionary update method is usually used to add new items or update existing items. For example:

dictionary1 = {"name": "John", "age": 33}
dictionary2 = {"job": "developer"}
dictionary1.update(dictionary2)
print(dictionary1)

The output of the above code would be {'name': 'John', 'age': 33, 'job': 'developer'} which shows that the dictionary2 has been added into dictionary1.

LEN Function

Python provides a built-in function called len that returns the number of key-value pairs in the dictionary. For example:

userInfo = {
'name': 'John',
'age': '24',
'location': 'USA'
}

print(len(userInfo))

The output of the above code is 3.

ITERATING Through a Dictionary

Dictionaries in Python can be iterated using a standard for loop. For example:

userInfo = {
'name': 'John',
'age': '24',
'location': 'USA'
}

for key, value in userInfo.items():
       print(key, value)

The output of the above is:

name John
age 24
location USA

Nested Dictionaries

Nested dictionaries in Python are dictionaries that reside within another dictionary. These can be incredibly useful when we are dealing with more complex data, where the structure required is hierarchical.

Let’s look into a basic example of how to create a nested dictionary:

student = {
"John": {
      "Age": 20,
      "Grade": "Junior",
      "Major": "Computer Science"
},
"Jane": {
      "Age": 22,
      "Grade": "Senior",
      "Major": "Mechanical Engineering"
      }
}

In the above example, the outer dictionary contains student names as keys and their details (another dictionary) as values. Each inner dictionary then contains different keys (Age, Grade, Major) paired with their respective values.

Accessing Nested Dictionaries

Accessing elements in a nested dictionary involves specifying each key in hierarchical order.

Let’s look into the example above and access John’s age:

print(student["John"]["Age"])  # Output: 20

To access John’s age, first reference the key John in the outer dictionary, which gives us the inner dictionary. Then we directly reference the key Age within the inner dictionary.

Modifying Nested Dictionaries

To modify a nested dictionary you simply target the specific keys in the dictionary and assign them new values.

For example, if John changed his major, you could update it like this:

student["John"]["Major"] = "Electrical Engineering"

print(student["John"])
# Output: {'Age': 20, 'Grade': 'Junior', 'Major': 'Electrical Engineering'}

Remember to always maintain the readability of your code when using nested dictionaries. It might become confusing to work with very deep nested dictionaries. Try to balance between nested dictionaries and readability to make your code efficient and understandable.

Dictionary Comprehensions

Dictionary comprehension is a concise and memory-friendly way to create and initialize dictionaries in one line of Python code. It’s a powerful tool in Python that allows you to convert a list or any other iterable into a dictionary in a single line.

The basic syntax of a dictionary comprehension in Python is:

{key_expression : value_expression for item in iterable}

Examples of Dictionary Comprehensions:

Let’s consider a few examples to Dictionary Comprehensions understand better:

  • Creating a dictionary with keys as numbers and their squares as values.
squares = {num: num*num for num in range(1, 6)}

print(squares)

This dictionary comprehension iterates over the range of numbers from 1 to 5 (end parameter in range() is exclusive) and for each number, it creates a key-value pair where the key is the number and the value is the square of the number.

Output of the above code will be: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

  • The following example creates a dictionary that maps a list of words back to themselves. This kind of dictionary is often used to look up the words efficiently.
words = ['apple', 'banana', 'cherry']
word_dict = {word : word for word in words}
print(word_dict)

The above code takes a list of words and iterates over it. For each word, it adds a key-value pair to the dictionary.

Output of the above code will be: {'apple': 'apple', 'banana': 'banana', 'cherry': 'cherry'}

  • You can also use conditional logic in our dictionary comprehensions:
even_squares = {x: x*x for x in range(10) if x % 2 == 0}
print(even_squares)

In the example above, we create a dictionary of squares for only the even numbers in the range of 0 to 9.

Output of the above code will be: {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

Real-world Applications of Dictionaries

Dictionaries in Python are well suited to a wide array of real-world applications. Because of their unique structure and functionality, they can often drastically simplify and optimize common tasks in Python.

Dictionaries in Python are primarily used for the following tasks:

  • Data Structuring: Dictionaries greatly simplify the task of storing and retrieving data.
person = {'name': 'John Doe', 'age': 29, 'occupation': 'Programmer'}
print(person['age'])  // Outputs: 29
  • Caching: Dictionaries can be used as a cache to speed up your program. This technique, known as memorization, can notably enhance the performance of programs with repeated calculations.
def fibonacci(n, memo = {}):
if n in memo:
      return memo[n]
if n <= 2:
      return 1
memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo)
return memo[n]
  • Counting: Dictionaries can be useful for counting the occurrence of items in a collection.
count = {}
words = ['red', 'blue', 'red', 'green', 'blue', 'blue']
for word in words:
    if word not in count:
              count[word] = 1
    else:
              count[word] += 1
    print(count)  #Outputs: {'red': 2, 'blue': 3, 'green': 1}

Performance Considerations

Python dictionaries are highly optimized. Balancing the design of your Python program with the proper implementation of dictionaries can drastically improve your code’s functionality and performance. They support insert, delete and search operations taking generally constant time – O(1). This is possible due to the concept of Hashing. Under the hood, Python uses a hash table allowing for high-performance operations.

When to Use Dictionaries

Although dictionaries are versatile, they aren’t appropriate for every situation:

  • Use a dictionary when you have a collection of items and you need to store and retrieve items by their identifiers or labels.
  • Use a dictionary when you’re dealing with substantial data and need to retrieve information quickly.

Do not use dictionaries when:

  • Your data does not have a unique key. In this case, a different data structure like a list would be more appropriate.
  • If you need to keep the data in order, dictionaries do not maintain any order until Python 3.7. In earlier versions, consider using an OrderedDict.

Further Reading and Resources

If you’re interested in going beyond what we’ve covered or want to learn Python at a more profound level, here are some useful resources:

  • Python Documentation: The Python official documentation is a comprehensive resource that provides detailed information on each aspect.

Official Python Documentation

  • Python Crash Course, Second Edition: A Hands-On, Project-Based Introduction to Programming by Eric Matthes. This is a great book for those who prefer learning by doing.
  • Automate the Boring Stuff with Python: Practical Programming for Total Beginners by Al Sweigart. This book is fantastic for beginners and focuses on real-world applications of Python programming.

Remember, the best way to master any programming concept, is by constant practice. So keep practicing and happy coding!

Read Also:

Leave a Comment

Your email address will not be published. Required fields are marked *