Python data structures: Differences between the list and the dictionary

List vs Dictionary

Python data structures: Differences between the list and the dictionary

Lists and Dictionaries are inbuilt data structures in Python. They are both helpful in storing and manipulating data. List stores values in a linear nature, while Dictionary stores values in key-value pairs.

This article aims to highlight the differences between the two data types and show you when they are most suitable for storing data.

You’re required to have a basic knowledge of the Python List and Dictionary to understand and follow through with this article.

What is a list?

A list is a built-in, ordered collection of elements or items. Items in a list can be of any data type, including numbers, strings, objects, or even other lists. Lists are versatile and widely used in Python to manipulate, organize, and store data. A list is created using square brackets [] and separating the items with a comma.

Examples of a list:

A list with the same data type.
List1 = [5, 10, 15, 20]
A list with multiple data types.
List2 = [5, ‘blue’, True, 1.5]
A multi-dimensional list.
List3 = [[‘blue’, ‘red’], [‘pasta’, ‘bread’]]

Check out Python Lists for more information about the Python list and how you can utilize it in storing and manipulating data.

What is a dictionary?

A dictionary is an ordered collection of items. It stores these items in pairs called the Key-value pair. Written in curly brackets ({}) and separated by a comma. However, a semicolon is placed between the key and its value to separate them. The key is a unique identifier for an item, and the value is the data associated with that key. The dictionary in Python is mutable. Which means you can change them after creation.

Examples of dictionaries in Python:

Dictionary with integer keys.
D1 = {
1: ‘oats’
2: ‘pasta’
3: ‘bread’
}
Dictionary with mixed keys
D2 = {
‘Name’: “Toria”
‘Weight’: 64
}

If you would like to learn more about Python dictionaries, you can check out this article.

NOTE: As of Python 3.7, the dictionary is an ordered data type. Older versions are unordered.

What are the differences between a Python list and a dictionary?

The following table shows the differences between a list and a dictionary in Python.

ParameterListDictionary
DefinitionA collection of items in a linear nature.A collection of items in key-value pairs.
SyntaxA list is created using square brackets [] and separating the items with a comma.The dictionary is created by placing the key-value pairs in a curly bracket {}. The key-value pair is separated with a semicolon.
Mode of accessYou can access the items or content using the index value.You can access the items using the keys.
Type of indexThe index of the list is the integer. And they start from 0.The dictionary keys can be of any data type.
MutabilityA list is mutable and can contain duplicate values.A dictionary is mutable but does not allow duplicate keys.
Count ()The number of a specified item in a list is obtained with the count() method.The count() method does not exist in Python dictionaries. To count the number of keys or values in a dictionary, you can use the len() function.
Order of itemsThe list always maintains the order of the items entered.Depending on the version of Python you are working with. Versions earlier than 3.7 do not maintain order.

When to use a dictionary vs. when to use a list

As a beginner, you might question the need to understand both list and dictionary data types, given that they seem to serve a similar purpose. This section aims to clarify when to use each data type by providing practical examples and evaluating their efficiency, using the space-trade trade-off.

Space-time trade-off between a list and a dictionary

A space-time trade-off, a time-memory trade-off, or the algorithmic space-time continuum in computer science, is a case where an algorithm or program trades increased space usage with decreased time. Wikipedia. Looking up an element with the dictionary is more efficient than using the list because it takes less time to iterate.

The following examples will show you the space-time trade-off between a list and a dictionary.

  • In this example, we will iterate over a whole list and dictionary to see which one takes less time to iterate.
# To calculate the time difference
import time

# Creating a dictionary
d1 = { 'a': "pasta", 'b': "bread", 'c': "Potato", 'd': "oat", 'e': "pancake", 'f': "corn", 'g': "rice", 'h': "juice", 'i': "plantain", 'j': "yam" }
x = time.time()

# Accessing elements
print("Accessing dictionary elements:") for key in d1: print(d1\[key\], end=" ")
y = time.time() print(f"\\nTime taken by dictionary: {x-y}")

# Creating a List
l1 = \["pasta", "bread", "potato", "oat", "pancake", "corn", "rice", "juice", "plantain", "yam"\]
x = time.time()
print("Accessing List elements:") for i in l1: print(i, end=" ")
y = time.time() print(f"\\nTime taken by list: {x-y}")
Output: 
Accessing dictionary elements: pasta bread Potato oat pancake corn rice juice plantain yam 
Time Taken by dictionary: 0.0004553794860839844

Accessing list elements: pasta bread potato oat pancake corn rice juice plantain yam 
Time Taken by list: 1.0

Explanation: In the above Python code, you can see that the dictionary took less time to loop through the elements. And the list took a longer time.

Note: Results or outputs may vary. Because other factors like your CPU speed, storage space, and even internet speed can affect the space-time trade-off.

  • Using the same list and dictionary we have created. In this example, you will see how long it takes to fetch a particular element from the list and the dictionary.
# To calculate the time difference
import time

# Creating a dictionary
d1 = { 'a': "pasta", 'b': "bread", 'c': "Potato", 'd': "oat", 'e': "pancake", 'f': "corn", 'g': "rice", 'h': "juice", 'i': "plantain", 'j': "yam" }

# Creating a list
l1 = \["pasta", "bread", "potato", "oat", "pancake", "corn", "rice", "juice", "plantain", "yam"\]

# time taken by dictionary
x = time.time() print(d1\['j'\]) 
y = time.time()
print(f"Time taken by dictionary:{x-y}")

# time taken by list
x = time.time() print(l1\[9\])
y = time.time()
print(f"Time taken by List:{x-y}")
Output: 
yam 
Time taken by dictionary: 0.0017747879028320312 
yam 
Time taken by list: 1.0

Explanation: The list took longer to fetch a single element from the list than the dictionary. This is because the dictionary uses a hashtable to implement the arrangement.

Note:

  • This program used the import statement to import the Python time module in the above examples. The time module allows us to retrieve the waiting time for code executions. You can visit the Python Documentation for more information on how the import system works.

  • Outputs or results may vary. Because factors like your CPU speed, storage space, and internet speed can affect the space-time trade-off.

Conclusion

In conclusion, this article has shed light on two fundamental inbuilt data structures in Python: lists and dictionaries. These structures are essential tools for storing and manipulating data, each with unique characteristics and use cases. When comparing the two, the choice between lists and dictionaries depends on the specific requirements of your data and the operations you intend to perform.

This article clarifies the differences between lists and dictionaries, thereby helping you make an informed decision when selecting the best data structure for your tasks.

References