Convert complex comma-separated string into Python dictionary

Question:

I am getting following string format from csv file in Pandas

"title = matrix, genre = action, year = 2000, rate = 8"

How can I change the string value into a python dictionary like this:

movie = "title = matrix, genre = action, year = 2000, rate = 8" 

movie = {
   "title": "matrix",   
   "genre": "action",   
   "year": "1964", 
   "rate":"8" 
}
Asked By: Behseini

||

Answers:

You can split the string and then convert it into a dictionary.
A sample code is given below

movie = "title = matrix, genre = action, year = 2000, rate = 8"
movie = movie.split(",")
# print(movie)
tempMovie = [i.split("=") for i in movie]
movie = {}
for i in tempMovie:
    movie[i[0].strip()] = i[1].strip()
print(movie)
Answered By: Vyshak Puthusseri

For the solution you can use regex

import re

input_user = "title = matrix, genre = action, year = 2000, rate = 8"

# Create a pattern to match the key-value pairs
pattern = re.compile(r"(w+) = ([w,]+)" )

# Find all matches in the input string
matches = pattern.findall(input_user)

# Convert the matches to a dictionary
result = {key: value for key, value in matches}

print(result)

The result:

{'title': 'matrix,', 'genre': 'action,', 'year': '2000,', 'rate': '8'}

I hope this can solve your problem.

movie = "title = matrix, genre = action, year = 2000, rate = 8" 

dict_all_movies = {}

for idx in df.index:
    str_movie = df.at[idx, str_movie_column]
    movie_dict = dict(item.split(" = ") for item in str_movie.split(", ")) 
    dict_all_movies[str(idx)] = movie_dict
Answered By: hongkail
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.