📌  相关文章
📜  Python|将键值对逗号分隔的字符串转换为字典

📅  最后修改于: 2022-05-13 01:54:47.129000             🧑  作者: Mango

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))
     
输出:


方法 #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))
     
输出:


方法 #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))
   
输出: