将复杂的逗号分隔字符串转换为Python字典

new9mtju  于 2023-02-15  发布在  Python
关注(0)|答案(3)|浏览(183)

我从Pandas中的csv文件中获取以下字符串格式
标题=矩阵,类型=动作,年份= 2000,比率= 8
如何将字符串值更改为python字典,如下所示:

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

movie = {
   "title": "matrix",   
   "genre": "action",   
   "year": "1964", 
   "rate":"8" 
}
btxsgosb

btxsgosb1#

您可以拆分字符串,然后将其转换为字典。

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)
zzoitvuj

zzoitvuj2#

对于解决方案,您可以使用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)

结果是:

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

希望这能解决你的问题。

ttvkxqim

ttvkxqim3#

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

相关问题