Python offers several fundamental data structures for storing data.
Among the most popular are:
Converting data from one type to another is essential to any dynamically typed programming language. Python, of course, is no exception.
This guide will explain in detail what lists and dictionaries are and demonstrate various ways to convert one type to another.
All examples in this article were executed using the Python interpreter version 3.10.12 on the Ubuntu 22.04 operating system, running on a Hostman cloud server.
A list in Python is an ordered data structure of the "index-value" type.
To create a list, use square brackets with values separated by commas:
my_list = [False, True, 2, 'three', 4, 5]
The list structure can be displayed in the console:
print(my_list)
The output will look like this:
[False, True, 2, 'three', 4, 5]
Accessing list values is done via indices:
print(my_list[0]) # Output: False
print(my_list[1]) # Output: True
print(my_list[2]) # Output: 2
print(my_list[3]) # Output: three
print(my_list[4]) # Output: 4
print(my_list[5]) # Output: 5
A dictionary in Python is an unordered data structure of the "key-value" type.
To create a dictionary, use curly braces with keys and values separated by colons and each pair separated by commas:
my_dict = {
'James': '357 99 056 050',
'Natalie': '357 96 540 432',
'Kate': '357 96 830 726'
}
You can display the dictionary structure in the console as follows:
print(my_dict)
The output will look like this:
{'James': '357 99 056 050', 'Natalie': '357 96 540 432', 'Kate': '357 96 830 726'}
Accessing dictionary values is done via keys:
print(my_dict['James']) # Output: 357 99 056 050
print(my_dict['Natalie']) # Output: 357 96 540 432
print(my_dict['Kate']) # Output: 357 96 830 726
You can convert a list to a dictionary in several ways:
Use the dict.fromkeys()
function, which creates a new dictionary with keys from the list.
Use a dictionary comprehension with auxiliary functions and conditional operators.
The latter option provides more flexibility for generating new dictionaries from existing lists.
The simplest way to create a dictionary from a list is to take the elements of a list instance and make them the keys of a dict instance. Optionally, you can add a default value for all keys in the new dictionary.
This can be achieved using the standard dict.fromkeys()
function. With this method, you can set a default value for all keys but not for individual keys.
Here is an example of creating such a dictionary with keys from a list:
objects = ['human', 'cat', 'alien', 'car'] # list of objects
objects_states = dict.fromkeys(objects, 'angry') # create a dictionary with a default value for all keys
objects_states_empty = dict.fromkeys(objects) # create a dictionary without specifying default values
print(objects_states) # output the created dictionary with values
print(objects_states_empty) # output the created dictionary without values
Console output:
{'human': 'angry', 'cat': 'angry', 'alien': 'angry', 'car': 'angry'}
{'human': None, 'cat': None, 'alien': None, 'car': None}
Another way to turn a list into dictionary keys is by using dictionary comprehension.
This method is more flexible and allows for greater customization of the new dictionary. In its simplest form, the comprehension iterates over the list and copies all its elements as keys into a new dictionary, assigning them a specified default value.
Here’s how to create a dictionary from a list using dictionary comprehension:
objects = ['human', 'cat', 'alien', 'car']
objects_states = {obj: 'angry' for obj in objects} # dictionary comprehension with a string as the default value
objects_states_empty = {obj: None for obj in objects} # dictionary comprehension with a default value of None
print(objects_states)
print(objects_states_empty)
Console output:
{'human': 'angry', 'cat': 'angry', 'alien': 'angry', 'car': 'angry'}
{'human': None, 'cat': None, 'alien': None, 'car': None}
In Python, the None
object is a special value (null in most programming languages) that represents the absence of a value. The None
object has a type of NoneType
:
print(type(None)) # Output: <class 'NoneType'>
A more advanced method is to use two lists to generate a dictionary: one for the keys and the other for their values.
For this purpose, Python provides the zip()
function, which allows iteration over multiple objects simultaneously. In simple loops, we can use this function like this:
objects = ['human', 'cat', 'alien', 'car']
states = ['walking', 'purring', 'hiding', 'driving']
for obj, state in zip(objects, states):
print(obj, state)
The console output will be:
human walking
cat purring
alien hiding
car driving
Thanks to this function, dictionary comprehension can simultaneously use elements from one list as keys and elements from another as values.
In this case, the syntax for dictionary comprehension is not much different from a simple iteration:
objects = ['human', 'cat', 'alien', 'car'] # list of future dictionary keys
states = ['walking', 'purring', 'hiding', 'driving'] # list of future dictionary values
objects_states = {obj: state for obj, state in zip(objects, states)} # dictionary comprehension iterating over both lists
print(objects_states)
Console output:
{'human': 'walking', 'cat': 'purring', 'alien': 'hiding', 'car': 'driving'}
A natural question arises: what happens if one of the lists is shorter than the other?
objects = ['human', 'cat', 'alien', 'car']
states = ['walking', 'purring']
objects_states = {obj: state for obj, state in zip(objects, states)}
print(objects_states)
The output will be:
{'human': 'walking', 'cat': 'purring'}
Thus, iteration in the dictionary comprehension stops at the shortest list.
The code above can be written in a very compact form using the dict()
constructor:
objects = ['human', 'cat', 'alien', 'car']
states = ['walking', 'purring', 'hiding', 'driving']
objects_states = dict(zip(objects, states)) # create a dictionary from two lists without a for loop
print(objects_states)
The console output will be the same as in the previous examples:
{'human': 'walking', 'cat': 'purring', 'alien': 'hiding', 'car': 'driving'}
In real-world applications, logic is often more complex than the simple examples shown earlier. Sometimes, you need to convert lists into dictionaries while applying specific conditions. For instance, some elements might need modification before inclusion in the dictionary or might not be included at all.
This can be achieved using conditions in dictionary comprehensions.
For example, we can exclude specific elements from the resulting dictionary:
objects = ['human', 'cat', 'alien', 'car']
states = ['walking', 'purring', 'hiding', 'driving']
objects_states = {obj: state for obj, state in zip(objects, states) if obj != 'alien'} # Protect Earth from unknown extraterrestrial influence
print(objects_states)
Console output:
{'human': 'walking', 'cat': 'purring', 'car': 'driving'}
We can refine the selection criteria further by introducing multiple conditions:
objects = ['human', 'cat', 'alien', 'car']
states = ['walking', 'purring', 'hiding', 'driving']
objects_states = {obj: state for obj, state in zip(objects, states) if obj != 'alien' if obj != 'cat'}
# Exclude the alien and the cat—who might be a disguised visitor from another galaxy
print(objects_states)
Console output:
{'human': 'walking', 'car': 'driving'}
When using multiple if
statements in a dictionary comprehension, they behave as if connected by a logical and
operator.
You can make dictionary generation even more flexible by combining if
and else
operators:
objects = ['human', 'cat', 'alien', 'car']
states = ['walking', 'purring', 'hiding', 'driving']
# In this example, all string elements in the first list are longer than those in the second list, except for 'cat'
objects_states = {
obj: ('[SUSPICIOUS]' if len(obj) < len(state) else 'calmly ' + state)
for obj, state in zip(objects, states)
}
# Mark the suspicious 'cat' appropriately and slightly modify other values
print(objects_states)
Console output:
{'human': 'calmly walking', 'cat': '[SUSPICIOUS]', 'alien': 'calmly hiding', 'car': 'calmly driving'}
In the earlier examples, we created dictionaries from two separate lists. But what if the keys and values needed for the new dictionary are contained within a single list?
In such cases, the logic of the dictionary comprehension needs to be adjusted:
objects_and_states = [
'human', 'walking', 'cat', 'purring', 'alien', 'hiding', 'car', 'driving'
] # Keys and values are stored sequentially in one list
objects_states = {
objects_and_states[i]: objects_and_states[i + 1] for i in range(0, len(objects_and_states), 2)
}
# The `range` function specifies the start, end, and step for iteration: range(START, STOP, STEP)
print(objects_states)
Console output:
{'human': 'walking', 'cat': 'purring', 'alien': 'hiding', 'car': 'driving'}
Sometimes, a list might contain nested dictionaries as elements. The values of these nested dictionaries can also be used to create a new dictionary.
Here’s how the logic changes in such cases:
objects = [
{'name': 'human', 'state': 'walking', 'location': 'street'},
{'name': 'cat', 'state': 'purring', 'location': 'windowsill'},
{'name': 'alien', 'state': 'hiding', 'location': 'spaceship'},
{'name': 'car', 'state': 'driving', 'location': 'highway'}
]
objects_states = {
obj['name']: obj['state'] for obj in objects
} # Extract 'name' as key and 'state' as value
print(objects_states)
Console output:
{'human': 'walking', 'cat': 'purring', 'alien': 'hiding', 'car': 'driving'}
This approach enables handling more complex data structures, such as lists of dictionaries, by targeting specific key-value pairs from each nested dictionary.
Converting a dictionary into a list in Python is a straightforward task, often better described as extracting data. From a single dictionary, you can derive several types of lists:
A list of keys
A list of values
A list of key-value pairs
Here’s how it can be done:
objects_states = {
'human': 'walking',
'cat': 'purring',
'alien': 'hiding',
'car': 'driving'
}
# Convert dictionary components to lists using the `list()` function
objects_keys = list(objects_states.keys()) # List of keys
objects_values = list(objects_states.values()) # List of values
objects_items = list(objects_states.items()) # List of key-value pairs
print(objects_keys)
print(objects_values)
print(objects_items)
Console output:
['human', 'cat', 'alien', 'car']
['walking', 'purring', 'hiding', 'driving']
[('human', 'walking'), ('cat', 'purring'), ('alien', 'hiding'), ('car', 'driving')]
Lists and dictionaries are fundamental data structures in Python, each offering distinct ways of storing and accessing data.
Dictionaries are more informative than lists, storing data as key-value pairs, whereas lists store values that are accessed by index.
Converting a dictionary into a list is straightforward, requiring no additional data since you’re simply extracting keys, values, or their pairs.
Converting a list into a dictionary, on the other hand, requires additional data or rules to map the list elements to dictionary keys and values.
There are a few methods to convert a List to Dictionary
Tool |
Key Values |
Syntax |
|
Common |
|
Dictionary Comprehension |
Common |
|
Dict Comp + |
Unique |
|
Dict Comp + |
Unique |
|
Dict Comp + |
Unique |
|
Complex lists may require more intricate dictionary comprehension syntax. Techniques shown in this guide, such as using zip()
and range()
for iterations, help handle such cases.
Converting a dictionary to a list is also possible in several ways, but it is much simpler.
Tool |
Extracts |
Syntax |
|
Keys |
|
|
Values |
|
|
Key-Value Pairs |
|
Python offers flexible and efficient ways to convert structured data types between lists and dictionaries, enabling powerful manipulation and access.