Dictionaries#

Dictionaries are a powerful and flexible data structure that allows you to work with key-value pairings. Unlike simpler data types like lists, dictionaries offer a more complex and organized way to manage data. They are a fundamental tool for storing and retrieving information efficiently in Python.

What is a Dictionary?#

A dictionary in Python is a data structure that associates keys with values. These keys act as unique identifiers for values, allowing for quick and efficient retrieval. Think of a dictionary like a real-world dictionary, where you look up a word (the key) to find its definition (the value). In Python, you can use curly braces {} to create a dictionary, and you separate each key-value pair with a colon (:). For example:

# A dictionary containing mountain elevations
mountain_elevations = {"mount jo": 3213.9, "gros mourne": 4392.1}
print(mountain_elevations)
{'mount jo': 3213.9, 'gros mourne': 4392.1}

This code defines a dictionary mountain_elevations with mountain names as keys and their elevations as values. When you print this dictionary, you’ll see the key-value pairs enclosed in curly braces.

Why Use Dictionaries?#

Dictionaries are invaluable in Python programming for several reasons:

  • Efficient Data Retrieval: Dictionaries provide lightning-fast access to values using keys. This makes them perfect for scenarios where you need to quickly look up information based on some identifier.

  • Structured Data: Dictionaries allow you to organize data in a structured way, associating related pieces of information. This structure is especially useful when dealing with complex data.

  • Dynamic Updates: You can easily add, modify, or remove key-value pairs within a dictionary, making it a flexible data structure for managing changing data.

Practical Use Cases#

Let’s explore some practical use cases to illustrate the power of dictionaries:

  1. Accessing Values: You can access values in a dictionary using keys. For example:

print(f"The elevation of Mount Jo is {mountain_elevations['mount jo']} feet.")
The elevation of Mount Jo is 3213.9 feet.
  1. Adding and Modifying Pairs: To add a new key-value pair or modify an existing one, simply assign a value to a key:

# Adding a new key-value pair
mountain_elevations['whiteface'] = 4867.3

# Modifying an existing pair
mountain_elevations['gros mourne'] = 4387.1

print(mountain_elevations)
{'mount jo': 3213.9, 'gros mourne': 4387.1, 'whiteface': 4867.3}
  1. Removing Pairs: You can delete key-value pairs using the del statement:

del mountain_elevations['gros mourne']
print(mountain_elevations)
{'mount jo': 3213.9, 'whiteface': 4867.3}
  1. Nesting Dictionaries: Dictionaries can be nested within other dictionaries or lists, creating complex data structures. For instance, you can create a list of dictionaries to represent different enemies in a video game:

infantry = {'name':'infantry', 'weapon':'a sword', 'hitpoints':50, 'damageInflicted':5, 'killPoints':30}
archer = {'name':'archer', 'weapon':'arrows', 'hitpoints':20, 'damageInflicted':10, 'killPoints':20}
catapult = {'name':'catapult', 'weapon':'flying rocks', 'hitpoints':10, 'killPoints':50}
enemies = [infantry, archer, catapult]

for enemy in enemies:
  print("When facing the " + enemy['name'].title() + 
     ", this enemy will try to kill you with " + enemy['weapon'].lower() +
     "! However, once you defeat the " + enemy['name'] + ", you will gain " + str(enemy['killPoints']) + " points.")
When facing the Infantry, this enemy will try to kill you with a sword! However, once you defeat the infantry, you will gain 30 points.
When facing the Archer, this enemy will try to kill you with arrows! However, once you defeat the archer, you will gain 20 points.
When facing the Catapult, this enemy will try to kill you with flying rocks! However, once you defeat the catapult, you will gain 50 points.

These nested dictionaries within a list allow you to organize and manage game-related information efficiently.

  1. Dictionaries Containing Lists: Dictionaries can also contain lists as their values. For example, you can use a dictionary to represent a customized pizza order:

my_pizza = {
    'crust': 'stuffed',
    'toppings': ['pepperoni', 'bacon', 'green pepper']
}

This dictionary contains a list of toppings as one of its values, demonstrating how dictionaries can handle diverse data structures.

Further Resources#

Socratica: Python Dictionaries