Python - Convert String into Dictionary


Python - Convert String into Dictionary

To convert a given string into dictionary in Python, first check the format in which the key-value pairs are present in the string.

If the given string is a JSON string, you can directly use json.loads() method to parse the given string into a dictionary.

But if the given string has key value pairs, where items are separated by a specific separator, and the key and value itself are separated by another specific separator.

For example, consider the following string.

"key1:value1,key2:value2"

Here, key and value are separated by colon separator, and items are separated by comma separator.

Let us consider another string.

"key1=value1,key2=value2"

Here, key and value are separated by equal-to character, and items are separated by comma separator.

So our first task is to find the key and value separator, and item separator. Then we can split the items and form key-value pairs from the splits.

In this tutorial, we shall go through two examples where we shall take a sample string, and convert this string into a dictionary.

  1. The first example is to take a JSON string, and convert this JSON string into a dictionary.
  2. The second example is to take a custom string, where there is a specific separator between items, and convert the string into a dictionary.

1. Convert JSON string into dictionary in Python

Consider that we are given a JSON string in x, and we have to convert this string x into a dictionary.

Steps

  1. Given a string in x.
x = '{"name": "apple", "quantity": 100}'
  1. Import json library at the start of program, call json.loads() method, and pass the given string x as argument.
json.loads(x)
  1. The json.loads() method returns a dictionary. Store it in a variable, and use it as per your requirement.
dictionary = json.loads(x)

Program

The complete program to convert a given JSON string into dictionary using json.loads().

Python Program

import json

# Given string
x = '{"name": "apple", "quantity": 100}'

# Convert jsong string into dictionary
dictionary = json.loads(x)

print(f"Dictionary\n{dictionary}")

Output

Dictionary
{'name': 'apple', 'quantity': 100}

2. Convert custom string into dictionary in Python

Consider that we are given a JSON string in x, and we have to convert this string x into a dictionary.

Steps

  1. Given a string in x.
x = 'name=apple,quantity=100,price=50'
  1. Identify the item separator. From the given string x, it is comma. Take a variable to hold the item separator.
item_sep = ','
  1. Identify the separator between key and value. From the given string x, it is equal to = character. Take a variable to hold the key and value separator.
key_value_sep = '='
  1. Split the given string x by item separator item_sep.
items = x.split(item_sep)
  1. For each item in items, split the item by key_value_sep. In this split, the first part is the key, and the second part is the value.
item.split(key_value_sep) # [0] is key, [1] is value

Program

The complete program to convert a given custom string into dictionary using string split operations is given below.

Python Program

import json

# Given string
x = 'name=apple,quantity=100,price=50'

# Item separator
item_sep = ','

# Key and value separator
key_value_sep = '='

# Take an empty dictionary to store the result
dictionary = dict() 

# Split items
items = x.split(item_sep)

# Iterate over items, split them into key and value, and add to dictionary
for item in items:
    key, value = item.split(key_value_sep)
    dictionary[key] = value

print(f"Dictionary\n{dictionary}")

Output

Dictionary
{'name': 'apple', 'quantity': '100', 'price': '50'}

You may make the code concise using dict() built-in function, and combining the fourth and fifth steps.

Python Program

import json

# Given string
x = 'name=apple,quantity=100,price=50'

# Item separator
item_sep = ','

# Key and value separator
key_value_sep = '='

# Convert string to dictionary
dictionary = dict(item.split(key_value_sep) for item in x.split(item_sep))

print(f"Dictionary\n{dictionary}")

Output

Dictionary
{'name': 'apple', 'quantity': '100', 'price': '50'}

Summary

In this tutorial, we learned how to convert a string into dictionary based on whether the given string is a JSON string or a custom string, with an example program explained for each of the use cases, with detailed steps.