How to Convert a List to a Dictionary in Python

sonia jessica
Level Up Coding
Published in
5 min readMar 14, 2022

--

Before we dive into the conversion of a list to a dictionary let us first understand what exactly they represent and why do we use them.

List and dictionary are a type of data structures. What are data structures you may ask?

The answer itself lies in the name. A data structure simply means some sort of a structure that is used to handle, store and use data in an efficient and effective manner. They help in organizing data so that various operations such as insertion, deletion, updating can be done quickly. We can relate it to our room. Like if in our room there is a place for everything and all commodities are arranged in an organized manner then it becomes easy for us to find anything in the room. Similarly, the main idea of using data structures is to may our job easy and efficient.

LIST

The list is a linear data structure that is capable of storing values of different data types together in one place. Some key features of a list in python are:-

  • They are dynamic in nature which essentially means that their size is not fixed. This property alone makes them very useful.
  • Values of a list can be accessed using indexes.
  • A single list can store data of different data types.
  • Indexes can be both positive and negative.

Different Functionalities of a List: Run Code

Python provides a number of functions related to a list. Let us see them and understand them one by one through some actual code:-

# initialize and empty list
l = []
# insert one single element in the list
l.append(5)
# insert multiple elements in the list
l.append(6.9)
l.append(7)
l.append(-6)
print("List after insertions: ",l) # l = [5,6.9,7,-6] → current state of the list# access and print an element from the list using both positive and #negative indexes
print("Access element from positive and negative index:",l[3],l[-1]) # -6,-6
# removing an element from the list
l.remove(7)
# [5,6.9,-6]
# iterating in a list
print("Print list using iteration")
for i in range(0,len(l)):
print(l[i])
Output:-
List after insertions: [5, 6.9, 7, -6]
Access element from positive and negative index: -6 -6
Print list using iteration
5
6.9
-6
  • append(): this function is used to insert an element at the end of the list
    Syntax: listName.append(element)
  • remove(): this function is used to remove an element from the list
    Syntax: listName.remove(element)
  • len(): this function is used to find the length of the list
    Syntax : len(listName)

Time Complexities of operations in a List

Given that there are N elements in a list let us observe the time complexities of various operations:-

  • Insertion: Since we have to traverse the entire list to insert/append an element at the end of the list time complexity for insertion will be O(N).
  • Deletion: In this case as well we will have to traverse the array to find the element that we want to delete so the time complexity for deletion will be O(N).
  • Access ith element: Since we can access any element in the list using it index time complexity for this operation is O(1).

Dictionary

It is another data structure that stores data in form of key-value pairs. Internally they use the concept of hashing for making these pairs.

They are used in places where any kind of mapping is required. It is a very powerful data structure that is used very frequently not only to optimize a solution but to store data in a meaningful way. The most common example is where a dictionary is used in JSON. Data in JSON is stored in key-value pairs which makes it easy to understand and use. Some of the key features of dictionaries are:-

  • In order to store data in a dictionary a key and value must always be specified.
  • Keys of a dictionary must be unique and immutable.
  • Values of a dictionary can be of any data type.
  • There are various ways to access values but the most simple method is through keys just like values of lists can be accessed through indexes same can be done using keys in the case of dictionaries.
def dictionary_operations():
# Create an dictionary
d = {}
# Add elements in a dictionary
d['a'] = 1
d['b'] = 2
d['c'] = 3
# Print the dictionary
print("Print the dictionary")
print(d)
print("Iterate and print the key value pairs in the dictionary")# iterate and print the dictionary
for i in d:
print(i,d[i])
dictionary_operations()
OUTPUT
Print the dictionary
{'c': 3, 'a': 1, 'b': 2}
Iterate and print the key value pairs in the dictionary
c 3
a 1
b 2

Conversion of List to Dictionary:

  1. Two different lists of the same sizes: In this will we have two separate lists in which elements of one list will act as a key and another as value.
keyList = ['a','b','c','d']
valueList = [1,2,3,4]
d = {}
for i in range(len(keyList)):
d[keyList[i]] = valueList[i]
print(d)
Output : {'d': 4, 'a': 1, 'c': 3, 'b': 2}

NOTE: In the above case since dictionaries are unordered the key-value pairs will be paired perfectly but their order is not maintained. To achieve this we can use the zip() function.

The way zip() function works have been demonstrated above.

keyList = ['a','b','c','d']
valueList = [1,2,3,4]
d = zip(keyList,valueList)
# since zip returns an object we need to change it to dictionary
d = dict(d)
print(d)
Output : {'a': 1, 'c': 3, 'b': 2, 'd': 4}

2. A single list

In this case, we have to create a dictionary from a single list with keys and values as given below:

Input : [‘x’, 1, ‘y’, 2, ‘z’, 3]
Output : {‘x’: 1, ‘y’: 2, ‘z’: 3}

a = ['x', 1, 'y', 2, 'z', 3]# First we have to create an iterable of the array 
# To use the zip function later on
iterable = iter(a)
resultantDict = dict(zip(iterable,iterable))
print(resultantDict)
output:{'x': 1, 'y': 2, 'z': 3}

--

--