Python | Initializing dictionary with list index-values

Python | Initializing dictionary with list index-values

To initialize a dictionary with list index-values, you can use a dictionary comprehension. This is an elegant and Pythonic way to map each element of the list to its corresponding index. Here's a basic example:

# Given a list my_list = ['a', 'b', 'c', 'd'] # Create a dictionary where list values are keys and indices are values my_dict = {value: index for index, value in enumerate(my_list)} print(my_dict) # Output: {'a': 0, 'b': 1, 'c': 2, 'd': 3} 

In the above code:

  • enumerate(my_list) gives us an iterator of tuples containing indices and the corresponding elements from my_list.
  • The dictionary comprehension {value: index for index, value in enumerate(my_list)} maps each value in the list to its index.

If you need the indices to be values in a list for each unique key, for a list with duplicate items, you can use collections.defaultdict to accumulate the indices in a list:

from collections import defaultdict # Given a list (potentially with duplicates) my_list = ['a', 'b', 'a', 'c', 'd', 'b'] # Create a dictionary where each list value is a key, and the value is a list of indices where it appears my_dict = defaultdict(list) for index, value in enumerate(my_list): my_dict[value].append(index) print(dict(my_dict)) # Output: {'a': [0, 2], 'b': [1, 5], 'c': [3], 'd': [4]} 

In this second example:

  • defaultdict(list) creates a dictionary that by default creates an empty list for each new key.
  • The loop goes through the list, and for each element, appends the current index to the list of indices for that element.

More Tags

select-query catplot mapstruct aggregation selenium openpgp amazon-sns doctrine symlink access-keys

More Programming Guides

Other Guides

More Programming Examples