Dictionary in Python

In Python, dictionaries are a type of data structure that store key-value pairs. They are unordered, mutable, and indexed by keys, which can be of any immutable data type (like strings, numbers, or tuples). Values associated with keys can be of any data type.

Creating a Dictionary in Python

You can create dictionaries using curly braces { }, with each key-value pair separated by a colon :. The keys in a dictionary act as indexes, similar to how lists are indexed by numbers. However, unlike lists, dictionaries are indexed by keys, which can be any immutable data type, such as strings or numbers. Dictionary keys are case-sensitive.

Syntax for Creating a Dictionary

The basic syntax to create a dictionary is:

dictionary_name = {
    key_1: value_1,
    key_2: value_2,
    key_3: value_3,
    ...
    key_n: value_n
}

Here's a breakdown:

  • Opening Curly Braces {: Used to start the dictionary.
  • Closing Curly Braces }: Used to end the dictionary.
  • Comma-Separated List: Each key-value pair is separated by a comma ,.
  • Key-Value Pair: Each key is separated from its value by a colon :.

Example of Creating a Dictionary

dictionary.py
colors = {
    "r": "red",
    "y": "yellow",
    "o": "orange",
    "b": "black",
    "g": "green"
}
 
print(colors) # Output: {'r': 'red', 'y': 'yellow', 'o': 'orange', 'b': 'black', 'g': 'green'}

In this example:

  • The keys are "r", "y", "o", "b", and "g".
  • The values associated with these keys are "red", "yellow", "orange", "black", and "green".

Characteristics of Dictionary Keys

  • Immutable: Dictionary keys must be of an immutable data type, like strings or numbers. Lists cannot be used as keys because they can be modified in place.
  • Unique: Duplicate keys are not allowed in a dictionary. If you try to use a key that already exists, the old value will be overwritten with the new one.

Example with Mixed Data Types

mixed_dict = {
   "portable": "laptop",
    7: 6,
    4: "eniv"
}
 
print(mixed_dict) # Output: {'portable': 'laptop', 7: 6, 4: 'eniv'}

Here, mixed_dict contains keys and values of different types, showing that Python dictionaries can store a variety of data types.

Creating an Empty Dictionary

You can create an empty dictionary by using a pair of curly braces without including any key-value pairs.

empty_dictionary = {}
print(empty_dictionary)
# Output: {}

Order of Key-Value Pairs

In dictionaries, the order of key-value pairs does not matter. Python ensures that as long as the keys and values are the same, the order won't affect equality.

pizza = {"pepperoni": 3, "calzone": 5, "margherita": 4}
fav_pizza = {"margherita": 4, "pepperoni": 3, "calzone": 5}
 
print(pizza == fav_pizza)  # Output: True

In this example, even though the order of key-value pairs is different, both dictionaries are considered equal.

Prior to Python 3.6, dictionaries were unordered collections. However, starting from Python 3.6, dictionaries maintain the insertion order of key-value pairs, meaning that they remember the order in which items were added.

Accessing and Modifying Key-Value Pairs in Dictionaries

In Python, dictionaries allow you to store, access, and modify data using key-value pairs. Each key in a dictionary is associated with a specific value, and you can retrieve or modify these values by referencing their keys.

Accessing Values in a Dictionary

To access the value associated with a specific key in a dictionary, you use square brackets [] containing the key. This key is used to locate the corresponding value in the dictionary.

Syntax:

value = dictionary_name[key]

Example:

cars = {
    "Tesla Model 3": 2017,
    "Ford Mustang": 1964,
    "Toyota Corolla": 1966,
    "Volkswagen Beetle": 1938,
    "Chevrolet Corvette": 1953
}
 
# Accessing the value associated with the key "Toyota Corolla"
corolla_launch_year = cars["Toyota Corolla"]
print(corolla_launch_year)    # Output: 1966

In this example, the key "Toyota Corolla" is used to retrieve the value 1966.

Modifying Values and Adding New Key-Value Pairs

Dictionaries are mutable, which means you can modify the values of existing keys or add new key-value pairs. To update a value, you simply assign a new value to the key. If the key does not exist in the dictionary, a new key-value pair is added.

Syntax:

dictionary_name[key] = new_value

Example:

# Modifying the value associated with the key "Tesla Model 3"
cars["Tesla Model 3"] = 2024
 
# Adding a new key-value pair for "Honda Civic"
cars["Honda Civic"] = 1972

After executing the above code:

  • The value for "Tesla Model 3" is updated from 2017 to 2024.
  • A new key "Honda Civic" is added with the value 1972.

Example with Updated Dictionary

cars = {
    "Tesla Model 3": 2017,
    "Ford Mustang": 1964,
    "Toyota Corolla": 1966,
    "Volkswagen Beetle": 1938,
    "Chevrolet Corvette": 1953
}
 
cars["Tesla Model 3"] = 2024
cars["Honda Civic"] = 1972
print(cars)
 
# Output: {'Tesla Model 3': 2024, 'Ford Mustang': 1964, 'Toyota Corolla': 1966, 'Volkswagen Beetle': 1938, 'Chevrolet Corvette': 1953, 'Honda Civic': 1972}

Handling Non-Existent Keys

If you try to access a key that doesn't exist in the dictionary, Python will raise a KeyError.

Example:

print(cars["nano"])
# Raises KeyError: 'nano'

To avoid this, you can use the in operator to check if a key exists in the dictionary before trying to access it.

Example:

cars = {
    "Tesla Model 3": 2017,
    "Ford Mustang": 1964,
    "Toyota Corolla": 1966,
    "Volkswagen Beetle": 1938,
    "Chevrolet Corvette": 1953
}
 
if "nano" in cars:
    print(cars["nano"])
else:
    print("Key not found")
# Output: Key not found

Checking for Key Presence

You can check whether a key is present in a dictionary using the in and not in membership operators, which return True or False.

Example:

clothes = {
    "rainy": "raincoats",
    "summer": "tees",
    "winter": "sweaters"
}
 
# Check if "spring" is a key in the dictionary
print("spring" in clothes)  # Output: False
print("spring" not in clothes)  # Output: True

In this example, since "spring" is not a key in the clothes dictionary, the output is False for "spring" in clothes and True for "spring" not in clothes.

Creating Dictionaries with the dict() Function

The dict() function is a built-in function in Python used to create dictionaries. This function can be used with keyword arguments or iterables.

Syntax:

dictionary = dict(key1=value1, key2=value2, ...)

Example:

numbers = dict(one=1, two=2, three=3)
print(numbers)  # Output: {'one': 1, 'two': 2, 'three': 3}

Here, one=1, two=2, and three=3 are converted into key-value pairs within the numbers dictionary.

Creating a Dictionary from Iterables

You can also create dictionaries from iterables, like a list of tuples where each tuple contains a key-value pair.

Syntax:

dictionary = dict(iterable)

Example:

pairs = [('vine', 1234), ('eniv', 4467), ('justin', 3214)]
phonebook = dict(pairs)
print(phonebook)  # Output: {'vine': 1234, 'eniv': 4467, 'justin': 3214}

The dict() function takes the list of tuples and converts them into a dictionary.

Built-In Functions Used on Dictionaries

Python provides several built-in functions that can be used to operate on dictionaries. These functions help in performing various tasks, such as finding the length of a dictionary, checking if all or any keys evaluate to True, and sorting the dictionary based on keys or values.

FunctionDescription
len()Returns the number of items (key-value pairs) in the dictionary.
all()Returns True if all keys in the dictionary are True; otherwise, returns False.
any()Returns True if any key in the dictionary is True; otherwise, returns False.
sorted()Returns a sorted list of keys in the dictionary by default. Can also sort by values or items (key-value pairs).

Examples of Using Built-In Functions on Dictionaries

Let's go through some examples to understand how these functions work.

  1. len()

    The len() function returns the number of key-value pairs in the dictionary.

    cars = {
        "Tesla Model 3": 2017,  # Correct
        "Ford Mustang": 1964,   # Correct
        "Toyota Corolla": 1966,  # Correct
        "Volkswagen Beetle": 1938, # Correct
        "Chevrolet Corvette": 1953 # Correct
    }
     
    # Get the number of key-value pairs in the dictionary
    num_items = len(cars)
    print(num_items)  # Output: 5
  2. all()

    The all() function returns True if all keys in the dictionary evaluate to True. If any key is False, it returns False.

    all_dict_func = {0: True, 2: False}
    all_true = all(all_dict_func)
    print(all_true)  # Output: False
     
    all_dict_func = {1: True, 2: False}
    all_true = all(all_dict_func)
    print(all_true)  # Output: True

    In the first example, since 0 is considered False, all(all_dict_func) returns False. In the second example, since both keys are non-zero (and thus True), all(all_dict_func) returns True.

  3. any()

    The any() function returns True if at least one key in the dictionary evaluates to True. If all keys are False, it returns False.

    any_dict_func = {0: False, 2: True}
    any_true = any(any_dict_func)
    print(any_true)   # Output: True

    Here, since 2 is True, any(any_dict_func) returns True.

  4. sorted()

    The sorted() function returns a sorted list of the dictionary's keys by default. You can also sort by values or items (key-value pairs).

    Sort by Keys:

    cars = {
        "Tesla Model 3": 2017,
        "Ford Mustang": 1964,
        "Toyota Corolla": 1966,
        "Volkswagen Beetle": 1938,
        "Chevrolet Corvette": 1953
    }
    sorted_keys = sorted(cars)
    print(sorted_keys)
    # Output: ['Chevrolet Corvette', 'Ford Mustang', 'Tesla Model 3', 'Toyota Corolla', 'Volkswagen Beetle']
     
    # Sort in descending order
    sorted_keys_desc = sorted(cars, reverse=True)
    print(sorted_keys_desc)
    # Output: ['Volkswagen Beetle', 'Toyota Corolla', 'Tesla Model 3', 'Ford Mustang', 'Chevrolet Corvette']

    In the above examples:

    • sorted() returns a list of sorted keys, values, or key-value pairs based on the specified criteria.
    • By default, sorting is done in ascending order, but you can reverse it by using reverse=True.

    Sort by Values

    cars = {
        "Tesla Model 3": 2017,
        "Ford Mustang": 1964,
        "Toyota Corolla": 1966,
        "Volkswagen Beetle": 1938,
        "Chevrolet Corvette": 1953
    }
    sorted_values = sorted(cars.values())
    print(sorted_values)
    # Output: [1938, 1953, 1964, 1966, 2017]

    The sorted() function then sorts these values in ascending order, which means from the smallest to the largest year.

    Sort by Items

    cars = {
        "Tesla Model 3": 2017,
        "Ford Mustang": 1964,
        "Toyota Corolla": 1966,
        "Volkswagen Beetle": 1938,
        "Chevrolet Corvette": 1953
    }
    sorted_items = sorted(cars.items())
    print(sorted_items)
    # Output: [('Chevrolet Corvette', 1953), ('Ford Mustang', 1964), ('Tesla Model 3', 2017), ('Toyota Corolla', 1966), ('Volkswagen Beetle', 1938)]

    The sorted() function sorts these tuples by the first element of each tuple (the key, which is the car model name) in alphabetical order.

Dictionary Methods

Dictionaries in Python offer a variety of methods to manage and manipulate the key-value pairs they contain. These methods allow you to add, update, remove, and access data in a dictionary efficiently.

Various Dictionary Methods

MethodSyntaxDescription
clear()dictionary_name.clear()Removes all key-value pairs from the dictionary.
fromkeys()dictionary_name.fromkeys(seq[, value])Creates a new dictionary from a sequence of elements with a specified value.
get()dictionary_name.get(key[, default])Returns the value associated with a key, or the default value if the key is not found.
items()dictionary_name.items()Returns a view object containing key-value pairs as tuples.
keys()dictionary_name.keys()Returns a view object containing all the keys in the dictionary.
pop()dictionary_name.pop(key[, default])Removes a key from the dictionary and returns its value. If the key is not found, returns the default value or raises a KeyError.
popitem()dictionary_name.popitem()Removes and returns an arbitrary key-value pair from the dictionary. If the dictionary is empty, raises a KeyError.
setdefault()dictionary_name.setdefault(key[, default])Returns the value of a key if it exists, otherwise inserts the key with a specified default value.
update()dictionary_name.update([other])Updates the dictionary with key-value pairs from another dictionary or iterable.
values()dictionary_name.values()Returns a view object containing all the values in the dictionary.

Examples of Using Dictionary Methods

  1. clear() The clear() method removes all key-value pairs from the dictionary.

    box_office_billion = {
        "avatar": 2009,
        "titanic": 1997,
        "starwars": 2015,
        "harrypotter": 2011,
        "avengers": 2012
    }
     
    # Clear all entries in the dictionary
    box_office_billion.clear()
    print(box_office_billion)  # Output: {}
  2. fromkeys()

    The fromkeys() method creates a new dictionary from a sequence of keys, each associated with a specified value.

    keys = ["avatar", "titanic", "starwars"]
    new_dict = dict.fromkeys(keys)
    print(new_dict)   # Output: {'avatar': None, 'titanic': None, 'starwars': None}
     
    # With a specified value
    new_dict_with_value = dict.fromkeys(keys, "billion_dollar")
    print(new_dict_with_value)
    # Output: {'avatar': 'billion_dollar', 'titanic': 'billion_dollar', 'starwars': 'billion_dollar'}
  3. get()

    The get() method retrieves the value of a key if it exists, or returns a default value if the key is not found.

    box_office_billion = {
        "avatar": 2009,
        "titanic": 1997,
        "starwars": 2015,
        "harrypotter": 2011,
        "avengers": 2012
    }
     
    value = box_office_billion.get("frozen")
    print(value)   # Output: None
     
    value_with_default = box_office_billion.get("frozen", 2013)
    print(value_with_default)  # Output: 2013
  4. items(), keys(), and values()

    These methods return view objects representing the dictionary's items (key-value pairs), keys, and values.

    box_office_billion = {
     "avatar": 2009,
     "titanic": 1997,
     "starwars": 2015,
     "harrypotter": 2011,
     "avengers": 2012
    }
     
    # Get all items (key-value pairs)
    items = box_office_billion.items()
    print(items)
    # Output: dict_items([('avatar', 2009), ('titanic', 1997), ('starwars', 2015), ('harrypotter', 2011), ('avengers', 2012)])
     
    # Get all keys
    keys = box_office_billion.keys()
    print(keys)
    # Output: dict_keys(['avatar', 'titanic', 'starwars', 'harrypotter', 'avengers'])
     
    # Get all values
    values = box_office_billion.values()
    print(values)
    # Output: dict_values([2009, 1997, 2015, 2011, 2012])
  5. pop()

    The pop() method removes a specified key and returns its value.

    box_office_billion = {
        "avatar": 2009,
        "titanic": 1997,
        "starwars": 2015,
        "harrypotter": 2011,
        "avengers": 2012
    }
    removed_value = box_office_billion.pop("avatar")
    print(removed_value)    # Output: 2009
  6. popitem()

    The popitem() method removes and returns an arbitrary (key, value) pair from the dictionary.

    box_office_billion = {
     "avatar": 2009,
     "titanic": 1997,
     "starwars": 2015,
     "harrypotter": 2011,
     "avengers": 2012
    }
    removed_item = box_office_billion.popitem()
    print(removed_item)    # Output: ('avengers', 2012)
  7. setdefault()

    The setdefault() method returns the value of a key if it exists. If the key does not exist, it inserts the key with a specified default value.

    box_office_billion = {
     "avatar": 2009,
     "titanic": 1997,
     "starwars": 2015,
     "harrypotter": 2011,
     "avengers": 2012
    }
     
    default_value = box_office_billion.setdefault("minions")
    print(default_value)   # Output: None
     
    default_value_with_specified_value = box_office_billion.setdefault("ironman", 2013)
    print(default_value_with_specified_value)      # Output: 2013
  8. update()

    The update() method adds key-value pairs from another dictionary or iterable to the current dictionary.

    box_office_billion = {
     "avatar": 2009,
     "titanic": 1997,
     "starwars": 2015,
     "harrypotter": 2011,
     "avengers": 2012
    }
     
    box_office_billion.update({"frozen": 2013})
    print(box_office_billion)
    # Output: {'titanic': 1997, 'harrypotter': 2011, 'avengers': 2012, 'minions': None, 'ironman': 2013, 'frozen': 2013}

Populating a Dictionary

One common way to populate a dictionary is to start with an empty dictionary {}, and then use the update() method to add key-value pairs. If the key does not exist, it will be created automatically.

countries = {}
countries.update({"Asia": "India"})
countries.update({"Europe": "Germany"})
countries.update({"Africa": "Sudan"})
 
print(countries)  # Output: {'Asia': 'India', 'Europe': 'Germany', 'Africa': 'Sudan'}

In this example, an empty dictionary countries is populated with key-value pairs using the update() function. Each update() call adds a new key-value pair to the dictionary.

Iterating Over Dictionaries

You can use a for loop to iterate over keys, values, or key-value pairs in a dictionary. By default, iterating over a dictionary with a for loop will iterate over its keys. To iterate over values, use the values() method, and to iterate over key-value pairs, use the items() method.

countries = {}
countries.update({"Asia": "India"})
countries.update({"Europe": "Germany"})
countries.update({"Africa": "Sudan"})
 
# Iterating over keys
for key in countries:
    print(key)
 
# Iterating over values
for value in countries.values():
    print(value)
 
# Iterating over key-value pairs
for key, value in countries.items():
    print(f"{key}: {value}")

In this example, the loop iterates over the keys, values, and key-value pairs of the countries dictionary.

Output

Asia
Europe
Africa
India
Germany
Sudan
Asia: India
Europe: Germany
Africa: Sudan

The del Statement

The del statement is used to delete a key-value pair from a dictionary. The syntax is straightforward:

del dict_name[key]

Here's an example:

animals = {"r": "raccoon", "c": "cougar", "m": "moose"}
print(animals)
# Output: {'r': 'raccoon', 'c': 'cougar', 'm': 'moose'}
 
del animals["c"]
print(animals)
# Output: {'r': 'raccoon', 'm': 'moose'}

In this example, the del statement removes the key-value pair "c": "cougar" from the animals dictionary.

How's article quality?

Last updated on -

Page Contents