How to create Python dictionary by enumerate function?

PythonServer Side ProgrammingProgramming

Python enumerate() function takes any iterable as argument and returns enumerate object using which the iterable can be traversed. It contains index and corresponding item in the iterable object like list, tuple or string.

Such enumerate object with index and value is then converted to a dictionary using dictionary comprehension.

>>> l1=['aa','bb','cc','dd']
>>> enum=enumerate(l1)
>>> enum

>>> d=dict((i,j) for i,j in enum)
>>> d
{0: 'aa', 1: 'bb', 2: 'cc', 3: 'dd'}
raja
Published on 16-Sep-2021 21:40:30
Advertisements