📜  Python – 将键值字符串转换为字典

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

Python – 将键值字符串转换为字典

有时,在使用Python字符串时,我们可能会遇到需要将字符串键值对转换为字典的问题。这可能有我们正在处理字符串数据并需要转换的应用程序。让我们讨论可以执行此任务的某些方式。

方法 #1:使用map() + split() + 循环
上述功能的组合可用于执行此任务。在此,我们使用 map 执行键值对到字典的转换,并使用 split() 完成键值对的拆分。

# Python3 code to demonstrate working of 
# Convert key-value String to dictionary
# Using map() + split() + loop
  
# initializing string
test_str = 'gfg:1, is:2, best:3'
  
# printing original string
print("The original string is : " + str(test_str))
  
# Convert key-value String to dictionary
# Using map() + split() + loop
res = []
for sub in test_str.split(', '):
    if ':' in sub:
        res.append(map(str.strip, sub.split(':', 1)))
res = dict(res)
  
# printing result 
print("The converted dictionary is : " + str(res)) 
输出 :
The original string is : gfg:1, is:2, best:3
The converted dictionary is : {'gfg': '1', 'is': '2', 'best': '3'}

方法 #2:使用dict() + generator expression + split() + map()
这是可以解决此问题的另一种方式。在此,我们以与上述类似的方式执行任务,但使用 dict() 和生成器表达式以 1 线性方式执行。

# Python3 code to demonstrate working of 
# Convert key-value String to dictionary
# Using dict() + generator expression + split() + map()
  
# initializing string
test_str = 'gfg:1, is:2, best:3'
  
# printing original string
print("The original string is : " + str(test_str))
  
# Convert key-value String to dictionary
# Using dict() + generator expression + split() + map()
res = dict(map(str.strip, sub.split(':', 1)) for sub in test_str.split(', ') if ':' in sub)
  
# printing result 
print("The converted dictionary is : " + str(res)) 
输出 :
The original string is : gfg:1, is:2, best:3
The converted dictionary is : {'gfg': '1', 'is': '2', 'best': '3'}