Split strings in list into key-value pairs (dict) in Python

avatar

Borislav Hadzhiev

Last updated: Jun 24, 2022

banner

Photo from Unsplash

Split strings in list into key-value pairs (dict) in Python #

To split strings in list into key-value pairs:

  1. Use a generator expression to split the strings in the list into nested lists of key-value pairs.
  2. Pass the two-dimensional list to the dict() class.
main.py
my_list = ['name=Alice', 'country=Austria', 'job=accountant'] result = dict(kv.split('=') for kv in my_list) # 👇️ {'name': 'Alice', 'country': 'Austria', 'job': 'accountant'} print(result)

We used a generator expression to split each string in the list into a 2-element list.

main.py
# 👇️ [['name', 'Alice'], ['country', 'Austria'], ['job', 'accountant']] print(list(kv.split('=') for kv in my_list))

The first item in each nested list is the name, and the second - the value.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

The dict() class can be passed an iterable of keyword arguments and returns a new dictionary.

If the values in your dictionary are integers, you can convert them using the int() class.

main.py
my_list = ['name=1', 'country=2', 'job=3'] def convert_to_int(kv): return (kv[0], int(kv[1])) result = dict(convert_to_int(kv.split('=')) for kv in my_list) # 👇️ {'name': 1, 'country': 2, 'job': 3} print(result)

The convert_to_int function gets called with a list containing 2 items - a key and a value.

It returns a tuple containing the key, and the value converted to an integer.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.