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:
- 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 theenumerate
function is used to loop through the listli
, 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
- Convert Matrix to Dictionary Value List - Python We are given a matrix and the task is to map each column of a matrix to customized keys from a list. For example, given a matrix li = [[4, 5, 6], [1, 3, 5], [3, 8, 1], [10, 3, 5]] and a list map_li = [4, 5, 6], the goal is to map the first column to the key 4, the second column to the key 5, and the 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
- Python - Pair lists elements to Dictionary Sometimes, while working with records we can have problems in which we can have pair of lists, we need to pair similar elements to a single key-value dictionary. This is a very peculiar problem but can have applications in data domains. Let us discuss certain ways in which this task can be performed 6 min read
- Python - Convert String List to Key-Value List dictionary Given a string, convert it to key-value list dictionary, with key as 1st word and rest words as value list. Input : test_list = ["gfg is best for geeks", "CS is best subject"] Output : {'gfg': ['is', 'best', 'for', 'geeks'], 'CS': ['is', 'best', 'subject']} Explanation : 1st elements are paired with 8 min read
- Convert List to Single Dictionary Key - Value list - Python We are given a list and a element K, our aim is to transform the given list into a dictionary where the specified element (Kth element) becomes the key and the rest of the elements form the value list. For example: if the given list is: [6, 5, 3, 2] and K = 1 then the output will be {5: [6, 3, 2]}.U 4 min read
- Python - Key Value list pairings in Dictionary Sometimes, while working with Python dictionaries, we can have problems in which we need to pair all the keys with all values to form a dictionary with all possible pairings. This can have application in many domains including day-day programming. Lets discuss certain ways in which this task can be 7 min read