Main Tutorials

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

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Christopher
3 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
3 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
3 years ago

how i can do reverse of 1.1