Introduction to Dictionary Data Structure

Welcome! Today, we're diving into Python dictionaries. These store items as key-value pairs, much like a real dictionary where you look up a word (key) to find its meaning (value). By the end of this lesson, you’ll have a good grasp of dictionaries.

Understanding Dictionaries

Dictionaries in Python are unordered collections of data values. This differentiation sets them apart from lists and tuples, which have specific orders. In a dictionary, each item possesses a key associated with a specific value, enhancing its efficiency in data access and management.

Here's a simple dictionary:

# A dictionary storing names as keys and ages as values
dictionary_example = {"Alice": 25, "Bob": 28, "Charlie": 30}
print(dictionary_example)  # Outputs: {'Alice': 25, 'Bob': 28, 'Charlie': 30}

In dictionary_example, the keys are "Alice", "Bob", and "Charlie", and the values are 25, 28, and 30, respectively. Key uniqueness is integral to the design of dictionaries - for example, that means we can only have a single key called "Alice".

Creating a Dictionary

Dictionaries are initiated by placing key-value pairs within {}. Another way to create a dictionary is by using a dict() method.

# An empty dictionary
empty_dict_1 = {} # an empty dictionary
empty_dict_2 = dict()   # another empty dictionary

# A dictionary of students and their ages
student_age = {"Alice": 12, "Bob": 13, "Charlie": 11}

Keys and values can be of different data types.

# A dictionary with diverse key and value types
student_info = {
    "name": "Alice",
    "age": 12,
    "subjects": ["Math", "Science", "English"],
    (90, 80): "Coordinates"    # Tuple used as a key
}
Accessing Dictionary Elements

Unlike lists, dictionaries are collections of items accessed by their keys, not by their positions.

print(student_age["Alice"])  # Outputs: 12

get() is a safer method for retrieving values as it returns None or a default value if the key is nonexistent.

print(student_age.get("David"))       # Outputs: None
print(student_age.get("David", 10))   # Outputs: 10

To check whether the key exists in the dictionary, use the in operator:

print("David" in student_age) # Outputs: False
print("Alice" in student_age) # Outputs: True
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal