Home > Software design >  How to convert string to dictionary using split
How to convert string to dictionary using split

Time:05-18

string = 'racknumber: 1 racktype: rack23 apn: rackansi2p height: 2134.0 width: 701.0'

output = {'racknumber': '1', 'racktype': 'rack23', 'apn': 'rackansi2p', 'height': '2134.0', 'width': '701.0'}

CodePudding user response:

If there is only 1 item per key, you can do like this

mystr = "racknumber: 1 racktype: rack23 apn: rackansi2p height: 2134.0 width: 701.0"
splitted = mystr.split()
mydic = {}

for i in range(len(splitted)):

    if i % 2 == 1:
        mydic[splitted[i-1]] = splitted[i]

CodePudding user response:

string = 'racknumber: 1 racktype: rack23 apn: rackansi2p height: 2134.0 width: 701.0'

l = sum((s.split() for s in string.split(':')), [])
d = dict(zip(l, l[1:]))
print(d)

Remarks:

  • flattening lists with sum( , []) is not recommended due to time complexity "issues". Use i.e. chain from itertools. For testing small stuffs on the fly... can be useful, I think.

Here with itertools

...
l = list(it.chain.from_iterable(s.split() for s in string.split(':')))
...
  • for more complex stuffs use regular expressions, see doc
import re

d = dict(re.findall(r'\b([^\s] ?):\s([^\s] )', string))
  • Related