Python – How to split string into a dict

Few Python examples to show you how to split a string into a dictionary.

1.1 Split a string into a dict.


#!/usr/bin/python

str = "key1=value1;key2=value2;key3=value3"

d = dict(x.split("=") for x in str.split(";"))

for k, v in d.items():
    print(k, v)

Output


key1 value1
key2 value2
key3 value3

1.2 Convert two list into a dict.


#!/usr/bin/python

str1 = "key1 | key2 | key3"
str2 = "value1 | value2 | value3"

keys = str1.split("|")
values = str2.split("|")

d = {}

for k in keys:
    k = k.strip()         # key trim
    for v in values:
        d[k] = v.strip()  # value trim

for k, v in d.items():
    print(k, v)

Output


key1 value1
key2 value2
key3 value3

1.3 zip example.


#!/usr/bin/python
str1 = "key1 | key2 | key3"
str2 = "value1 | value2 | value3"

keys = str1.split(" | ")
values = str2.split(" | ")

d = dict(zip(keys, values))

for k, v in d.items():
    print(k, v)

Output


key1 value1
key2 value2
key3 value3

References

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Christopher
5 years ago

Did you fake the output, example two is clearly wrong.

>>> str1 = “key1 | key2 | key3”
>>> str2 = “value1 | value2 | value3”
>>>
>>> keys = str1.split(“|”)
>>> values = str2.split(“|”)
>>>
>>> d = {}
>>>
>>> for k in keys:
…   k = k.strip()     # key trim
…   for v in values:
…     d[k] = v.strip() # value trim

>>> for k, v in d.items():
…   print(k, v)

key1 value3
key2 value3
key3 value3

Patrick
5 years ago

Example two works as:

str1 = “key1 | key2 | key3”
str2 = “value1 | value2 | value3”

keys = str1.split(“|”)
values = str2.split(“|”)

d = {}

for i, k in enumerate(keys):
  k = k.strip()
  d[k] = values[i].strip()

for k, v in d.items():
  print(k, v)

Jamil Noyda
5 years ago

how i can do reverse of 1.1