Tina
Tina

Reputation: 13

Creating dictionary from the string using python

I want to create a dictionary from the string like this below

" Car : 100 Bus: 200 Travel cost = 500 cycle : 10 bike : 50 "

and the output should look like below

{ 'car' : 100 , 'bus' : 200, 'Travel cost' : 500 ,  'cycle' : 10 , 'bike' : 50}

It has ":" and "=" in the string, so I am not understanding how to do, please help me. I tried:

Dict = dict((x.strip(), y.strip()) for x, y in (element.split(':') for element in string.split(' ')))

Upvotes: 0

Views: 91

Answers (1)

Bruno Vermeulen
Bruno Vermeulen

Reputation: 3455

It is quite hard to parse the string but let us assume the pattern in the string is:

'\D+ : \d+ \D+ : \d+'

where \D is a character and \d is a digit and divided by :, you may proceed as follows.

  • Sanitize the string and replace = with :
  • find all patterns for '\D+ : \d '
  • loop over the found pattern and convert to a dict

for example

import re
input_str = "Car : 100 Bus: 200 Travel cost = 500 cycle : 10 bike : 50 "
input_str = input_str.replace('=', ':')

dict_elements = re.findall(r'\D+ : \d+ ', input_str)

my_dict = {}
for element in dict_elements:
    key, val = element.split(':')
    key = key.strip()
    val = int(val.strip())
    my_dict[key] = val

print(my_dict)

actually a better solution dealing with possible spaces before and after the : is the following

import re
input_str = "Car:100 Bus: 200 Travel cost = 500 cycle: 10       bike      :50    "

dict_elements = re.findall(r'\s*(\D+)\s*[:=]\s*(\d+)\s*', input_str)

my_dict = {}
for element in dict_elements:
    my_dict[element[0].strip()] = int(element[1].strip())

print(my_dict)

Note I dealt with : or = in the search string of findall with [:=], while key is (\D+) and val is (\d+).

Upvotes: 1

Related Questions