![]() |
VOOZH | about |
We are given a list we need to convert it into the key- value pair. For example we are given a list li = ['apple', 'banana', 'orange'] we need to convert it to key value pair so that the output should be like {1: 'apple', 2: 'banana', 3: 'orange'}. We can achieve this by using multiple methods like enumerate, defaultdict and various approaches using loops.
enumerate()enumerate() generates an iterator that yields tuples of (index, value) for each element in an iterable start parameter allows you to specify the starting index for the enumeration, which defaults to 0.
{1: 'apple', 2: 'banana', 3: 'orange'}
Explanation:
Using a loop, initialize an empty dictionary and iterate over the list with enumerate, adding each index as a key and its corresponding element as the value.
{0: 'apple', 1: 'banana', 2: 'cherry'}
Explanation:
res is created, and the enumerate function is used to loop through the list li, providing both the index and the element of each item.res.zipUse zip to pair indices from range(len(li)) with elements from li, creating key-value pairs. Convert the zipped object into a dictionary using dict.
{0: 'apple', 1: 'banana', 2: 'cherry'}
Explanation:
defaultdictUse defaultdict from the collections module to initialize a dictionary with default values. Then by enumerating the list, where indices are the keys and elements are the values.
{0: 'apple', 1: 'banana', 2: 'cherry'}
Explanation: