How to create Python dictionary from list of keys and values?

PythonServer Side ProgrammingProgramming

If L1 and L2 are list objects containing keys and respective values, following methods can be used to construct dictionary object.

Zip two lists and convert to dictionary using dict() function

>>> L1 = ['a','b','c','d']
>>> L2 = [1,2,3,4]
>>> d = dict(zip(L1,L2))
>>> d
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

Using dictionary comprehension syntax

>>> L1 = ['a','b','c','d']
>>> L2 = [1,2,3,4]
>>> d = {k:v for k,v in zip(L1,L2)}
>>> d
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
raja
Published on 08-Feb-2018 19:11:15
Advertisements