Convert Each List Element to Key-Value Pair - Python
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:
- enumerate(list1, 1) creates an iterator that generates tuples of (index, value) for each element in the list starting the index from 1.
- dict() converts the iterator of tuples into a dictionary, where the index becomes the key and the value remains the same.
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:
- An empty dictionary
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. - During each iteration, the index is added as a key and the corresponding element as the value in the dictionary
res.
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:
- Zip pairs the indices (generated by range(len(li))) with the corresponding elements from the list li.
- Zip object is converted into a dictionary using dict(), where indices become keys and elements become values.
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:
- defaultdict(str) creates a dictionary that automatically assigns an empty string as the default value for missing keys.
- enumerate(li) pairs indices with elements from the list li and defaultdict stores them as key-value pairs, with indices as keys and elements as values.
Similar Reads
Python - Alternate list elements as key-value pairs Given a list, convert it into dictionary by mapping alternate elements as key-value pairs. Input : test_list = [2, 3, 5, 6, 7, 8] Output : {3: 6, 6: 8, 2: 5, 5: 7} Explanation : Alternate elements mapped to get key-value pairs. 3 -> 6 [ alternate] Input : test_list = [2, 3, 5, 6] Output : {3: 6,
2 min read
Convert Value List Elements to List Records - Python We are given a dictionary with lists as values and the task is to transform each element in these lists into individual dictionary records. Specifically, each list element should become a key in a new dictionary with an empty list as its value. For example, given {'gfg': [4, 5], 'best': [8, 10, 7, 9
3 min read
Python - Convert key-values list to flat dictionary We are given a list that contains tuples with the pairs of key and values we need to convert that list into a flat dictionary. For example a = [("name", "Ak"), ("age", 25), ("city", "NYC")] is a list we need to convert it to dictionary so that output should be a flat dictionary {'name': 'Ak', 'age':
3 min read
Python Convert Dictionary to List of Values Python has different types of built-in data structures to manage your data. A list is a collection of ordered items, whereas a dictionary is a key-value pair data. Both of them are unique in their own way. In this article, the dictionary is converted into a list of values in Python using various con
3 min read
Python - Convert Lists into Similar key value lists Given two lists, one of key and other values, convert it to dictionary with list values, if keys map to different values on basis of index, add in its value list. Input : test_list1 = [5, 6, 6, 6], test_list2 = [8, 3, 2, 9] Output : {5: [8], 6: [3, 2, 9]} Explanation : Elements with index 6 in corre
12 min read