Python|将键值对逗号分隔的字符串转换为字典
给定一个字符串,不同的键值对用逗号分隔,任务是将该字符串转换为字典。这些类型的问题在 Web 开发中很常见,我们从查询中获取参数或以字符串的形式获取响应。下面给出了一些解决任务的方法。
方法#1:使用字典理解
# Python3 code to demonstrate
# converting comma separated string
# into dictionary
# Initialising string
ini_string1 = 'name = akshat, course = btech, branch = computer'
# Printing initial string
print ("Initial String", ini_string1)
# Converting string into dictionary
# using dict comprehension
res = dict(item.split("=") for item in ini_string1.split(", "))
# Printing resultant string
print ("Resultant dictionary", str(res))
输出:
Initial String name = akshat, course = btech, branch = computer
Resultant dictionary {‘branch ‘: ‘ computer’, ‘name ‘: ‘ akshat’, ‘course ‘: ‘ btech’}
方法 #2:使用 Map 和 lambda
# Python3 code to demonstrate
# converting comma separated string
# into dictionary
# Initialising string
ini_string1 = 'name = akshat, course = btech, branch = computer'
# Printing initial string
print ("Initial String", ini_string1)
# Converting string into dictionary
# using map and lambda
res = dict(map(lambda x: x.split('='), ini_string1.split(', ')))
# Printing resultant string
print ("Resultant dictionary", str(res))
输出:
Initial String name = akshat, course = btech, branch = computer
Resultant dictionary {‘course ‘: ‘ btech’, ‘name ‘: ‘ akshat’, ‘branch ‘: ‘ computer’}
方法 #3:使用eval()
函数
# Python3 code to demonstrate
# converting comma separated string
# into dictionary
# Initialising string
ini_string1 = 'name ="akshat", course ="btech", branch ="computer"'
# Printing initial string
print ("Initial String", ini_string1)
# Converting string into dictionary
# using eval
res = eval('dict('+ini_string1+')')
# Printing resultant string
print ("Resultant dictionary", str(res))
输出:
Initial String name =”akshat”, course =”btech”, branch =”computer”
Resultant dictionary {‘course’: ‘btech’, ‘name’: ‘akshat’, ‘branch’: ‘computer’}