Converting each list element to key-value pair in Python


Lists are a commonly used data structure in python where data is stored in the form of elements. Key-value pairs are what we refer to as dictionaries where the data had unique keys and corresponding values. In this article, we are going to convert each list element into a key-value pair in Python.

Converting each list element to a key-value pair in Python is done to efficiently organize and retrieve data by associating each element with a unique key. This transformation enhances data structure, enables faster lookup operations, and provides a flexible and meaningful representation of the data, improving readability and facilitating key-based operations.

Example

Input: [6565, 49, 123321, 562, 73]
Output: {65: 65, 4: 9, 123: 321, 5: 62, 7: 3}

We will be converting the list elements into key value pairs by dividing the elements into 2 equal halves, the 1st half would be the key and 2nd half would be the values.

Method 1: For-each Loop

A for each loop provides a method of traversing each element within an iterable object such as an array, list or dictionary.

Code below uses a for-each loop and transforms an array of elements into a dictionary of key-value pairs using equal allocation for key and value per element, half the digits becoming key and half value - yielding transformed data as the dictionary output.

Example

def convert_to_key_value_pairs(elements):
   result = {}
   for num in elements:
      num_str = str(num)
      length = len(num_str)
      half_length = length // 2
       
      key = int(num_str[:half_length])
      value = int(num_str[half_length:])
       
      result[key] = value
   
   return result

elements = [6565, 49, 123321, 562, 73]
output = convert_to_key_value_pairs(elements)
print(output)

Output

{65: 65, 4: 9, 123: 321, 5: 62, 7: 3}

Method 2: Using List Comprehension and String Manipulation

List comprehension in Python offers an amazingly flexible yet compact and readable method of creating new lists by applying operations or transformations on existing ones or iterables, like lists or iterables. By concatenating this step with iteration over iterables or lists themselves into one line of code you can generate multiple new lists while iterating over original one with ease, often by square bracketing for easy reference - offering an effective means for filtering elements out, applying functions or altering data within any list.

String manipulation refers to the practice of changing or manipulating strings in various ways. Since Python strings are immutable, direct changes cannot occur directly. Instead, string manipulation methods exist that enable concatenation, slicing, replacement and splitting as well as case conversion among many others. With string manipulation comes an ability to extract parts from one string, combine multiple ones, change content within it as well as manipulate its structure for personal needs - it is an indispensable skill in text processing, data cleaning and string-based operations using Python.

Example

elements = [6565, 49, 123321, 562, 73]
output = {int(str(num)[:len(str(num)) // 2]): int(str(num)[len(str(num)) // 2:]) for num in elements}
print(output)

Output

{65: 65, 4: 9, 123: 321, 5: 62, 7: 3}

Method 3: Using Zip() and Map() Functions

The map() and zip() functions are used for data processing and manipulation, they are explained below.

zip()  The zip() function takes multiple iterables as arguments and returns an iterator of tuples, where each tuple contains elements from the input iterables paired together. It iterates over the iterables in parallel, combining corresponding elements into tuples. The resulting iterator stops when the shortest input iterable is exhausted. zip() is often used to aggregate or transpose data from multiple lists or iterables.

map()  The map() function applies a given function to each item in an iterable, and returns an iterator of its results. It takes in as arguments one or more iterables and one or more functions; then this function is applied individually for every element within these iterables before returning an iterator that contains their transformed values. map() can be particularly helpful when you want to perform similar operations on multiple items within one list or iterable.

Example

elements = [6565, 49, 123321, 562, 73]
output = dict(zip(map(lambda num: int(str(num)[:len(str(num)) // 2]), elements), map(lambda num: int(str(num)[len(str(num)) // 2:]), elements)))
print(output)

Output

{65: 65, 4: 9, 123: 321, 5: 62, 7: 3}

Method 4: Using Itertools and Iter() Function

The itertools module and it’s function iter() is popular for handling iterations and creating iterator objects.

itertools  the itertools library provides many functions for efficient and memory-friendly iteration, such as product(), permutations(), combinations() and chain() - some commonly used functions include this one that enable efficient generation of combinations, permutations and Cartesian products without explicitly storing their elements into memory.

Iter() Function in Python  This built-in function in Python returns an iterator object from an iterable. It accepts two arguments; an iterable object to create the iterator out of and an optional sentinel value to mark its end. The iter() function can be used when iterating over objects that support iteration such as lists, strings or custom iterable objects.

Example

import itertools
elements = [6565, 49, 123321, 562, 73]
iter_test_list = iter(elements)
output = {int(str(num)[:len(str(num)) // 2]): int(str(num)[len(str(num)) // 2:]) for num in itertools.islice(iter_test_list, len(elements))}
print(output)

Output

{65: 65, 4: 9, 123: 321, 5: 62, 7: 3}

Conclusion

Python provides several approaches for turning each list element into a key-value pair, including for-each loops, list comprehension with string manipulation, Zip() and Map() functions, Itertools module and Iter() functions, among others. We accomplished our desired transformation quickly and effortlessly using these approaches; these approaches offer flexibility, readability, efficiency as well as seamless data manipulation/transformation processes when it comes to turning list elements into key/value pairs.

Updated on: 18-Aug-2023

138 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements