Python | Split String and Convert to Dictionary

3/5 - (1 vote)

Summary: Use a list comprehension to split the given string twice, which returns a list of lists wherein each inner list contains the key-value pairs as individual items. Convert this nested list to a dictionary using the dict constructor.

Minimal Example:

info = '1:One;2:Two;3:Three'
print(dict([item.split(":") for item in info.split(";")]))
# OUTPUT: {'1': 'One', '2': 'Two', '3': 'Three'}

Problem Formulation

Problem: Given a string; How will you split the string using a specific separator and store the contents in a dictionary?

Example 1

# Input
info = 'Name:Bob;ID:1111;prof:scientist'
# Output
{'Name': 'Bob', 'ID': '1111', 'prof': 'scientist'}

Method 1: Using split and dict

Approach: Use a list comprehension and split the string at the given separator. This generates a list containing items that are in the form of key-value pairs. Go ahead and split this list with “:” as the separator which now creates a list of lists such that each inner list contains the key and the value as separate items within the list. Now convert this nested list to a dictionary using the dict method.


info = 'Name:Bob;ID:1111;prof:scientist'
print(dict([item.split(":") for item in info.split(";")]))

# {'Name': 'Bob', 'ID': '1111', 'prof': 'scientist'}


Note: Python’s built-in dict() function creates and returns a new dictionary object from the comma-separated argument list of key = value mappings. For example, dict(name = 'Alice', age = 22, profession = 'programmer') creates a dictionary with three mappings: {'name': 'Alice', 'age': 22, 'profession': 'programmer'}. A dictionary is an unordered and mutable data structure, so it can be changed after creation.

🌎Related Read: Python dict() — A Simple Guide with Video

Method 2: Using dict, map and lambda

Approach: The approach is quite similar to the one we followed in the previous solution. The only difference, in this case, is the usage of the split function which first splits the given string along the given separator and then a lambda function which is used to further split the items of the list returned by the split function using : as the separator. Effectively you are performing a couple of splits one by one and each split operation can be mapped to the other using the map function. The function returns a map object which can then be converted to a dictionary using the dict method and returned as an output.


info = 'Name:Bob;ID:1111;prof:scientist'
print(dict(map(lambda x: x.split(':'), info.split(';'))))

# OUTPUT: {'Name': 'Bob', 'ID': '1111', 'prof': 'scientist'}

Readers Digest:

  • A lambda function is an anonymous function in Python. It starts with the keyword lambda, followed by a comma-separated list of zero or more arguments, followed by the colon and the return expression. For example, lambda x, y, z: x+y+z would calculate the sum of the three argument values x+y+z.
  • The map() function transforms one or more iterables into a new one by applying a “transformator function” to the i-th elements of each iterable. The arguments are the transformator function object and one or more iterables. If you pass n iterables as arguments, the transformator function must be an n-ary function taking n input arguments. The return value is an iterable map object of transformed, and possibly aggregated, elements.


Before we wrap up, here’s a final exercise for you to test your grip on this topic.

Given: Given the following string and delimiter –

info = 'a-b-c'
deli = '-'

 Can you order the splits in the form of a dictionary?

Expected Output:

{0: 'a', 1: 'b', 2: 'c'}

Solution: To solve this challenge, you can split the given string using the split function. Now use the enumerate method to iterate through the items of the list containing the split strings. Note that enumerate also provides you a counter for each item in the list, which can be used as a key. Therefore, use this counter as a key and the item as the corresponding value and store them in a dictionary.

info = 'a-b-c'
deli = '-'

res = dict()
li = info.split('-')
for k, v in enumerate(li):
    res[k] = v

# {0: 'a', 1: 'b', 2: 'c'}

There are other ways of solving this question, but this was probably the simplest of solutions.


Hurrah! We have successfully solved the problem using two different ways and we also conquered a related problem. I hope this article helped you and it answered your queries. Please subscribe and stay tuned for more interesting discussions and solutions in the future.

Happy coding!

Check out my new Python book Python One-Liners (Amazon Link).

If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!

The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

Publisher Link: