Convert Each List Element to KeyValue Pair Python (original) (raw)

Last Updated : 24 Jan, 2025

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.

Using 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.

Python `

li = ['apple', 'banana', 'orange'] a = dict(enumerate(li, 1)) print(a)

`

Output

{1: 'apple', 2: 'banana', 3: 'orange'}

**Explanation:

Using a Loop

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.

Python `

li = ["apple", "banana", "cherry"]

Initialize an empty dictionary

res = {}

Iterate through the list with indices using enumerate

for index, value in enumerate(li): res[index] = value # Add index as key and element as value

print(res)

`

Output

{0: 'apple', 1: 'banana', 2: 'cherry'}

**Explanation:

Using zip

Use 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.

Python `

li = ["apple", "banana", "cherry"]

Create a dictionary by zipping a range of indices with the elements

res = dict(zip(range(len(li)), li))

print(res)

`

Output

{0: 'apple', 1: 'banana', 2: 'cherry'}

**Explanation:

Using defaultdict

Use 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.

Python `

from collections import defaultdict

li = ["apple", "banana", "cherry"]

Use defaultdict to create a dictionary where missing keys default to a string

res = defaultdict(str, enumerate(li))

print(dict(res)) # Convert defaultdict to a regular dictionary for display

`

Output

{0: 'apple', 1: 'banana', 2: 'cherry'}

**Explanation:

Similar Reads