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

3 comments on “Python – How to split string into a dict

  1. 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)

    Reply
  2. 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

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *