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 the Author

author image
mkyong
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

avatar