![]() |
VOOZH | about |
We are having a list we need to find index of each element and store it in form of dictionary. For example, a = ['a', 'b', 'c', 'd'] we need to find index of each elements in list so that output should be {'a': 0, 'b': 1, 'c': 2, 'd': 3}.
We can use dictionary comprehension to create a dictionary where each element of a list is mapped to its index. This is achieved by enumerating the list and constructing key-value pairs with elements as keys and their indices as values.
{'a': 0, 'b': 1, 'c': 2, 'd': 3}
Explanation:
enumerate(a) generates index-value pairs from list which are used in dictionary comprehension to create key-value pairs.We can use a for loop with enumerate() to iterate over the list and store each element as a key with its index as value in a dictionary. This approach builds dictionary step by step without using comprehension.
{'a': 0, 'b': 1, 'c': 2, 'd': 3}
Explanation:
dict() with zip()We can use dict(zip(lst, range(len(lst)))) to create a dictionary where each element of list is mapped to its index. zip() function pairs elements with their indices and dict() converts these pairs into a dictionary.
{'a': 0, 'b': 1, 'c': 2, 'd': 3}
Explanation: