Open In App

Difference between List and Dictionary in Python

Last Updated : 05 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Lists and Dictionaries in Python are inbuilt data structures that are used to store data. Lists are linear in nature whereas the dictionaries stored the data in key-value pair. In this article, we will see the difference between the two.

Lists in Python

Lists are just like arrays, declared in other languages. Lists need not be homogeneous always which makes it a most powerful tool in Python. A single list may contain data types like Integers, Strings, as well as Objects. Lists are mutable, and hence, even after their creation.

Example: In this example, we will see how to create a simple list as well as a multidimensional list in Python and access its values using the list index.

Python3




# Python program to demonstrate
# Lists
 
# Creating a List with
# the use of multiple values
List = ["Geeks", "For", "Geeks"]
print("List containing multiple values: ")
print(List[0]) 
print(List[2])
   
# Creating a Multi-Dimensional List
# (By Nesting a list inside a List)
List = [['Geeks', 'For'] , ['Geeks']]
print("\nMulti-Dimensional List: ")
print(List)


Output:

List containing multiple values: 
Geeks
Geeks

Multi-Dimensional List:
[['Geeks', 'For'], ['Geeks']]

Dictionary in Python

Python Dictionary on the other hand is an unordered collection of data values, used to store data values like a map, unlike other Data Types that hold only a single value as an element, Dictionary holds a key:value pair. Key-value is provided in the dictionary to make it more optimized. Each key-value pair in a Dictionary is separated by a colon (:) whereas each key is separated by a ‘comma’.

Example: In this example, we will see how to create a simple dictionary with similar key types as well as a dictionary with mixed key types.

Python3




# Creating a Dictionary 
# with Integer Keys
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("Dictionary with the use of Integer Keys: ")
print(Dict)
   
# Creating a Dictionary 
# with Mixed keys
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)


Output:

Dictionary with the use of Integer Keys: 
{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Dictionary with the use of Mixed Keys:
{1: [1, 2, 3, 4], 'Name': 'Geeks'}

Difference between a List and a Dictionary

The following table shows some differences between a list and a dictionary in Python:

List

Dictionary

The list is a collection of index value pairs like that of the array in C++.

The dictionary is a hashed structure of the key and value

pairs.

The list is created by placing elements in [ ] separated by commas “,”

The dictionary is created by placing elements in { } as “key”:”value”, each key-value pair is separated by commas “, “

The indices of the list are integers starting from 0.

The keys of the dictionary can be of any data type.

The elements are accessed via indices.

The elements are accessed via key-value pairs.

The order of the elements entered is maintained.

There is no guarantee for maintaining order.

Lists are orders, mutable, and can contain duplicate values. Dictionaries are unordered and mutable but they cannot contain duplicate keys.

Space-Time Trade-Off between List and Dictionary

It is more efficient to use a dictionary for the lookup of elements because it takes less time to traverse in the dictionary than a list.

Let’s consider a data set with 5000000 elements in a machine learning model that relies on the speed of retrieval of data. To implement this we have to choose wisely between two data structures i.e. list and dictionary. The dictionary is preferred because of less time and less space storage as dictionaries are implemented in the form of hash tables from Python 3.6 so it is never a space-time trade-off problem in dictionaries.

Example 1: In this example, we will iterate over the whole list and dictionary to see which is more efficient and takes less time to iterate.

Python3




# To calculate the time difference
import time
 
# Creating a dictionary
d ={'john':1, 'alex':2}
 
x = time.time()
 
# Accessing elements
print("Accessing dictionary elements:")
for key in d:
    print(d[key], end=" ")
 
y = time.time()
print("\nTime taken by dictionary:", y-x)
 
# Creating a List
c =[1, 2]
 
x = time.time()
 
print("\nAccessing List elements:")
for i in c:
    print(i, end=" ")
     
y = time.time()
print("\nTime taken by dictionary:", y-x)


Output:

Accessing dictionary elements:
1 2
Time taken by dictionary: 1.0013580322265625e-05

Accessing List elements:
1 2
Time taken by dictionary: 3.5762786865234375e-06

Example 2:

Here, in this example, we will see how much time is taken to fetch a particular element from a list or dictionary in Python. It will take more time to fetch a single element in a list than that of a dictionary because a dictionary uses hashtable for implementing the arrangement.

Python3




# Program to fetch particular
# elements of structure
 
import time
 
# Creating dictionary and list
dict_name ={"bob":12, "john":11}
list_name =[2, 3, 4, 5, 1]
 
# Time taken by dictionary
x = time.time()
L = dict_name["bob"]
y = time.time()
print("Time taken by dictionary:", y-x)
 
# Time taken by list
x = time.time()
L = list_name[2]
y = time.time()
print("\nTime taken by list:", y-x)


Output:

Time taken by dictionary: 9.5367431640625e-07

Time taken by list: 4.76837158203125e-07


Similar Reads

Convert Dictionary Value list to Dictionary List Python
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to convert dictionary list to nested records dictionary taking each index of dictionary list value and flattening it. This kind of problem can have application in many domains. Let's discuss certain ways in which this task can be performed. Input : test_list =
9 min read
Python program to update a dictionary with the values from a dictionary list
Given a dictionary and dictionary list, update the dictionary with dictionary list values. Input : test_dict = {"Gfg" : 2, "is" : 1, "Best" : 3}, dict_list = [{'for' : 3, 'all' : 7}, {'and' : 1, 'CS' : 9}] Output : {'Gfg': 2, 'is': 1, 'Best': 3, 'for': 3, 'all': 7, 'and': 1, 'CS': 9} Explanation : All dictionary keys updated in single dictionary. I
8 min read
Python Program to create a sub-dictionary containing all keys from dictionary list
Given the dictionary list, our task is to create a new dictionary list that contains all the keys, if not, then assign None to the key and persist of each dictionary. Example: Input : test_list = [{'gfg' : 3, 'is' : 7}, {'gfg' : 3, 'is' : 1, 'best' : 5}, {'gfg' : 8}]Output : [{'is': 7, 'best': None, 'gfg': 3}, {'is': 1, 'best': 5, 'gfg': 3}, {'is':
8 min read
Python - Append Dictionary Keys and Values ( In order ) in dictionary
Given a dictionary, perform append of keys followed by values in list. Input : test_dict = {"Gfg" : 1, "is" : 2, "Best" : 3} Output : ['Gfg', 'is', 'Best', 1, 2, 3] Explanation : All the keys before all the values in list. Input : test_dict = {"Gfg" : 1, "Best" : 3} Output : ['Gfg', 'Best', 1, 3] Explanation : All the keys before all the values in
5 min read
Python - Combine two dictionaries having key of the first dictionary and value of the second dictionary
Given two dictionaries. The task is to merge them in such a way that the resulting dictionary contains the key from the first dictionary and the value from the second dictionary. Examples: Input : test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}, test_dict2 = {"Gfg2" : 26, "is2" : 20, "best2" : 70} Output : {'Gfg': 26, 'is': 20, 'best': 70} Expla
8 min read
Python | Convert flattened dictionary into nested dictionary
Given a flattened dictionary, the task is to convert that dictionary into a nested dictionary where keys are needed to be split at '_' considering where nested dictionary will be started. Method #1: Using Naive Approach Step-by-step approach : Define a function named insert that takes two parameters, a dictionary (dct) and a list (lst). This functi
8 min read
Python | Convert nested dictionary into flattened dictionary
Given a nested dictionary, the task is to convert this dictionary into a flattened dictionary where the key is separated by '_' in case of the nested key to be started. Method #1: Using Naive Approach Step-by-step approach : The function checks if the input dd is a dictionary. If it is, then it iterates over each key-value pair in the dictionary, a
8 min read
Convert String Dictionary to Dictionary Python
Interconversions of data types have been discussed many times and have been quite a popular problem to solve. This article discusses yet another problem of interconversion of the dictionary, in string format to a dictionary. Let's discuss certain ways in which this can be done. Convert String Dictionary to Dictionary Using json.loads() This task ca
6 min read
Python | Dictionary initialization with common dictionary
Sometimes, while working with dictionaries, we might have an utility in which we need to initialize a dictionary with records values, so that they can be altered later. This kind of application can occur in cases of memoizations in general or competitive programming. Let’s discuss certain way in which this task can be performed. Method 1: Using zip
7 min read
Python - Update dictionary with other dictionary
Sometimes, while working with Python dictionaries, we can have problem in which we need to perform the update of dictionary with other keys of dictionary. This can have applications in domains in which we need to add certain records to previously captured records. Let's discuss certain ways in which this task can be performed. Method #1 : Using loo
9 min read
Article Tags :
Practice Tags :