Python Dictionaries - The Key Ingredient to Data Mastery

Rinu Gour
PythonFlood
Published in
7 min readJul 4, 2023

--

Python dictionaries are a powerful tool for storing and accessing data in Python. They allow you to store key-value pairs, similar to how words and definitions are stored in a real-life dictionary.

With dictionaries, you can easily retrieve information by its key and update or remove data as needed.

By learning how to use dictionaries effectively, you can improve the efficiency and functionality of your Python programs.

Python Dictionaries

In Python, a dictionary is a collection of key-value pairs. Think of a dictionary as a real-life dictionary, where the keys are the words and the values are their definitions.

Let’s say we want to create a dictionary of fruits and their colors. We can do this in Python using curly braces {} and separating each key-value pair with a colon :
For example:

fruit_colors = {"apple": "red", "banana": "yellow", "grape": "purple"}

In this example, “apple”, “banana”, and “grape” are the keys, and “red”, “yellow”, and “purple” are their corresponding values.

We can access the values in the dictionary using the keys. For example, to get the color of an apple, we would write:

print(fruit_colors["apple"])

This would output “red”, since “red” is the value associated with the key “apple”.

We can also add new key-value pairs to the dictionary using the same syntax.
For example, to add a “pear” with a value of “green” to the dictionary, we would write:

fruit_colors["pear"] = "green"

Now, if we were to print the dictionary again, we would see that it includes the new key-value pair:

print(fruit_colors)

This would output: {‘apple’: ‘red’, ‘banana’: ‘yellow’, ‘grape’: ‘purple’, ‘pear’: ‘green’}

One important thing to note about dictionaries is that they are mutable, which means we can change their values after they have been created.

For example, let’s say we made a mistake and accidentally assigned the wrong color to a fruit. We can update the value associated with the key by simply assigning a new value to that key:

fruit_colors["apple"] = "green"

Now, if we were to print the dictionary again, we would see that the value for “apple” has been updated:

print(fruit_colors)

This would output: {‘apple’: ‘green’, ‘banana’: ‘yellow’, ‘grape’: ‘purple’, ‘pear’: ‘green’}

We can also use the del keyword to remove key-value pairs from the dictionary.

For example, let’s say we no longer need the “pear” key-value pair in our dictionary. We can remove it like this:

del fruit_colors["pear"]

Now, if we were to print the dictionary again, we would see that the “pear” key-value pair has been removed:

print(fruit_colors)

This would output: {‘apple’: ‘green’, ‘banana’: ‘yellow’, ‘grape’: ‘purple’}

It’s important to note that keys in a dictionary must be unique. If we try to assign a value to a key that already exists, it will overwrite the previous value.

For example, let’s say we add another key-value pair to our dictionary:

fruit_colors["grape"] = "green"

This will overwrite the previous value associated with the “grape” key. Now, if we were to print the dictionary again, we would see that the value for “grape” has been updated:

print(fruit_colors)

This would output: {‘apple’: ‘green’, ‘banana’: ‘yellow’, ‘grape’: ‘green’}

Finally, we can use various dictionary methods to access information about our dictionaries. For example, we can use the keys() method to get a list of all the keys in the dictionary:

print(fruit_colors.keys())

This would output: dict_keys([‘apple’, ‘banana’, ‘grape’])

We can also use the values() method to get a list of all the values in the dictionary:

print(fruit_colors.values())

This would output: dict_values([‘green’, ‘yellow’, ‘green’])

And we can use the items() method to get a list of all the key-value pairs in the dictionary:

print(fruit_colors.items())

This would output: dict_items([(‘apple’, ‘green’), (‘banana’, ‘yellow’), (‘grape’, ‘green’)])

Ordered or Unordered

In Python, dictionaries are used to store data in key-value pairs. A dictionary can be either ordered or unordered, depending on the version of Python you’re using.

In Python 3.6 and earlier, dictionaries were unordered. This means that the order in which you add items to the dictionary is not preserved when you iterate over it. For example:

my_dict = {'a': 1, 'c': 3, 'b': 2}
for key in my_dict:
print(key)

In this code, the order of the keys printed out by the loop is not guaranteed to be the same as the order in which they were added to the dictionary.

However, in Python 3.7 and later, dictionaries are guaranteed to maintain the order in which items are added. This means that the same code as above will always produce the keys in the same order:

my_dict = {'a': 1, 'c': 3, 'b': 2}
for key in my_dict:
print(key)

This change was introduced in Python 3.7 as part of the language specification, so it’s guaranteed to work the same way in all implementations of Python 3.7 and later.

Whether or not you need an ordered dictionary depends on your use case. If you don’t care about the order in which items are stored or retrieved, an unordered dictionary may be sufficient.

However, if you need to preserve the order of the items, for example if you’re building a JSON object or a list of menu items, then an ordered dictionary can be very useful.

Changeable

dictionaries in Python are also changeable, meaning that you can add, remove, and modify items after the dictionary is created. This makes them a very versatile and powerful data structure in Python.

Duplicates

dictionaries in Python do allow duplicates, but they don’t allow duplicate keys. Each key in a dictionary must be unique, but the values can be duplicated.

If you try to add a new key to a dictionary that already exists, the new value will overwrite the existing value associated with that key. For example:

my_dict = {'a': 1, 'b': 2, 'c': 3, 'b': 4}
print(my_dict)

In this code, the value associated with the key ‘b’ is overwritten by the new value of 4. When you print the dictionary, you’ll see that the output is {‘a’: 1, ‘b’: 4, ‘c’: 3}.

So, while dictionaries in Python do allow duplicated values, they don’t allow duplicated keys.

Data Types

​​In Python, dictionaries store data in key-value pairs, where each key is unique and maps to a corresponding value. The values in a dictionary can be of any data type, including:

  • Numbers (integers, floats, etc.)
  • Strings
  • Booleans
  • Lists
  • Tuples
  • Dictionaries
  • And more!

In fact, the values in a dictionary can be any data type that can be stored in a variable. The keys, on the other hand, must be immutable data types such as strings, numbers, or tuples.

To access the items in a dictionary, you can use the keys as the index. For example, if you have a dictionary of student names and their grades:

grades = {'Alice': 90, 'Bob': 85, 'Charlie': 92}

You can access the grade for Alice by using her name as the key:

alice_grade = grades['Alice']

In this example, alice_grade would be set to 90, which is Alice’s grade.
Overall, dictionaries are a very powerful and flexible data structure in Python that can be used to store and manipulate a wide variety of data types.

Nested Dictionary

A nested dictionary is a dictionary that contains one or more dictionaries as values. This can be useful when you want to store more complex data structures, such as a table, in a dictionary.

Let’s say you want to store information about a student’s grades in different subjects. You could use a nested dictionary to represent this data, where each subject is a key in the outer dictionary, and the corresponding value is another dictionary that contains the student’s grades for that subject:

grades = {
'math': {'Alice': 90, 'Bob': 85, 'Charlie': 92},
'science': {'Alice': 87, 'Bob': 90, 'Charlie': 85},
'english': {'Alice': 95, 'Bob': 92, 'Charlie': 90}
}

In this example, grades is a dictionary that contains three keys: ‘math’, ‘science’, and ‘english’. The value for each key is another dictionary that contains the student’s grades for that subject.To access the grades for a specific student in a specific subject, you can use nested indexing, like this:

alice_math_grade = grades['math']['Alice']

In this example, alice_math_grade would be set to 90, which is Alice’s grade in math.

Overall, nested dictionaries can be a useful tool when you need to store more complex data structures in a dictionary, such as a table or a matrix.

Tips and Tricks

Here are some tips and tricks for working with Python dictionaries:

  1. Use descriptive keys: When choosing keys for your dictionary, make sure they are descriptive and easy to remember. This will make it easier for you and others to understand and use your dictionary.
  2. Use the get() method: When accessing values in a dictionary, you can use the get() method to avoid getting an error if the key doesn’t exist. This method returns None if the key is not found, rather than raising a KeyError.
  3. Use the setdefault() method: If you want to set a default value for a key that doesn’t exist yet in the dictionary, you can use the setdefault() method. This method sets the value of the key if it doesn’t exist, and returns the value of the key if it does exist.
  4. Use dictionary comprehension: If you need to create a new dictionary based on an existing one, you can use dictionary comprehension to do so in a concise and efficient manner.
  5. Use in keyword to check if a key exists: You can use the in keyword to check if a key exists in a dictionary. This is a convenient and readable way to check if a key is present in the dictionary before trying to access its value.
  6. Use items() method for iteration: The items() method can be used to iterate over both keys and values of a dictionary. This is a handy way to process all key-value pairs in the dictionary at once.
  7. Use copy() method to create a copy: If you need to create a copy of a dictionary, you can use the copy() method. This creates a new dictionary with the same key-value pairs as the original.

Conclusion:

In conclusion, Python dictionaries are an essential tool for anyone working with Python.

By understanding how to use dictionaries effectively, you can store and access data more efficiently, saving time and improving the functionality of your programs. Whether you are working on a small personal project or a large-scale application, mastering dictionaries will be a valuable skill that you can use in your programming endeavors.

--

--

Data Science Enthusiast | Research writer | Blogger | Entrepreneur