Back to course

Dictionaries 1: Key-Value Pairs and Creation

Python Programming: The 0 to Hero Bootcamp

Dictionaries: Mapping Data

Dictionaries are Python's implementation of a hash map or associative array. They store data in key-value pairs. This allows for extremely fast retrieval of values based on the key.

Dictionaries are unordered (in Python versions before 3.7, though ordered in 3.7+), mutable, and the keys must be unique and immutable (like strings, numbers, or tuples).

Dictionaries are defined using curly braces {} with key-value pairs separated by colons (:).

Creating Dictionaries

python

Key: String, Value: Integer

person = {'name': 'Jane', 'age': 30, 'city': 'London'}

Empty dictionary

empty_dict = {}

Using the dict() constructor

settings = dict(theme='dark', notifications=True) print(settings)

Accessing Values

Access values using the key inside square brackets [].

python print(person['name']) # Output: Jane

WARNING: Accessing a key that doesn't exist raises a KeyError.

print(person['occupation']) # KeyError

Getting Values Safely (.get())

Use .get(key, default_value) to retrieve a value. If the key is not found, it returns the default_value instead of raising an error.

python occupation = person.get('occupation', 'Unemployed') print(occupation) # Output: Unemployed