python

How to convert a list of key-value pairs to dictionary Python

In this tutorial, we are going to see how to convert a list of key-value pairs to dictionary in Python and display them using the print() function.
 

Example:
Input: ['a', 1, 'b', 2, 'c', 3, 'd', 4]
Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

 

 

How to convert a list of key-value pairs to dictionary Python
def list_to_dict(li):
    dct = {li[i]: li[i + 1] for i in range(0, len(li), 2)}
    return dct
         
li = ['a', 1, 'b', 2, 'c', 3, 'd', 4]
print(list_to_dict(li))

Output:

{'a': 1, 'b': 2, 'c': 3, 'd': 4}
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *