top of page

Understanding Python Dictionaries

Updated: Feb 17, 2023

Python dictionaries are a fundamental data structure in the Python programming language. A dictionary contains key-value pairs, where each key is unique and is associated with a specific value. This article will explore how Python dictionaries can be created, manipulated, and common functions/methods used in conjunction.



Creating Python Dictionaries

There are several ways to create a Python dictionary. The most common method is to use curly braces {} separating the keys and values by colons. For example, the following example creates a dictionary with three items:

my_dict = {"name": "John", "age": 30, "city": "New York"}

Another way to create a dictionary is to use the built-in dict() function. This method requires a list of tuples, where each tuple contains only one key and a value. Below is an example of this.

my_dict = dict([("name", "John"), ("age", 30), ("city", "New York")])
print(my_dict)

# Output: {'name': 'John', 'age': 30, 'city': 'New York'}


Accessing Elements

A dictionary wouldn't be much use if we couldn't access the individual items contained within the dictionary. To extract values, we use the following format:

dictionary[key]

where `dictionary` is the variable holding the Python dictionary and `key` is the identifier for the value you want to extract. Here's an example using the `my_dict` variable to extract the individual's name.

my_dict = {"name": "John", "age": 30, "city": "New York"}
name = my_dict["name"]  # Get value assigned to the "name" key
print(name)

# Output: John

Alternatively, you can use the `get` method to extract a value from the Python dictionary. Here's an example using the `get` method on the `my_dict` variable to extract the city.

my_dict = {"name": "John", "age": 30, "city": "New York"}
city = my_dict.get("city")  # Get value assigned to the "city" key
print(city)

# Output: New York


Manipulating Python Dictionaries

Python dictionaries are mutable, meaning their contents can be modified after creation. The most common way to add or modify a key-value pair is to use the square brackets [] and the assignment operator (=). Below is an example of changing the value associated with the "age" key in the `my_dict` variable.

my_dict = {"name": "John", "age": 30, "city": "New York"}
print(my_dict)  # Before modification
my_dict["age"] = 35
print(my_dict)  # After modification

# Output Before: {'name': 'John', 'age': 30, 'city': 'New York'}
# Output After:  {'name': 'John', 'age': 35, 'city': 'New York'}

You can also add a new key-value pair to the dictionary after it has been created. To do this, you again use the bracket notation shown in the last example; only this time, you specify a key that does not exist in the dictionary. Let's add a new key called "gender" to the `my_dict` variable.

my_dict = {"name": "John", "age": 30, "city": "New York"}
my_dict["gender"] = "male"  # Add new key-value pair
print(my_dict)

# Output: {'name':'John', 'age':30, 'city':'New York', 'gender':'male'}


Common Functions and Methods

Function/Method

Definition

dict(iterable)

Converts an iterable to a dictionary

len(iterable)

Returns the number of items in a list

dict.items()

Returns a list of key-value pairs in a dictionary

dict.keys()

Returns a list of all keys in a dictionary

dict.values()

Returns a list of all values in a dictionary

dict.get(key, default=None)

Returns the value assigned to a key and returns a default value if the key is not found

dict.update(iterable)

Adds new key-value pair to a dictionary​ where iterable is an object with key-value pairs

Note that "dict." in the table is the variable that contains the dictionary you want to manipulate.



Using Python's `dict` Function

The `dict` function converts an iterable that contains key-value pairs into a dictionary. Below is an example of converting a list of tuples into a dictionary.

my_list = [('a', 1), ('b', 2), ('c', 3)]
my_dict = dict(my_list)
print(my_dict)

# Output: {'a': 1, 'b': 2, 'c': 3}


Using Python's `len` Function

The `len` function takes an iterable as an argument and returns the number of elements within the iterable. In our case, we provide a dictionary (the iterable), and the function will count the total number of items (elements) in the dictionary and return the count. Below is an example of finding the number of entries in a dictionary.

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

# Output: 3


Using Python's `items` Method

The `items` method returns an iterable containing tuples of length two where the first element is the key and the second the value. Below is an example of iterating over a dictionary with a for loop and unpacking both the key and value.

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

# Output:
#    a 1
#    b 2
#    c 3


Using Python's `keys` Method

The `keys` method returns an iterable containing all keys defined in the dictionary. Below is an example showing how to print all keys in a dictionary.

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

# Output:
#    a
#    b
#    c


Using Python's `values` Method

The `values` method returns an iterable containing all values defined in the dictionary. Below is an example showing how to print all values in a dictionary.

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

# Output:
#    1
#    2
#    3

Using Python's `get` Method

The `get` method takes a key as an argument and returns the value associated with the passed key. If the provided key is not found, a default value is returned. Below are two examples, one when the key is defined in the dictionary and one when it is not.


Key defined
my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict.get("c")
print(value)

Output: 3

Key not defined
my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict.get("d", -1)
print(value)

Output: -1


Using Python's `update` Method

The `update` method updates the values of existing keys in a dictionary or adds new key-value pairs from an iterable, typically another dictionary, if the key does not exist. Below are two examples, one where the key exits and the other when it does not.


Key defined
my_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict.update({'a': 9})
print(my_dict)

Output: {'a': 9, 'b': 2, 'c': 3}

Key not defined
my_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict.update({'d': 4})
print(my_dict)

Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}


6 views0 comments

Recent Posts

See All
bottom of page