将具有键和值的字符串转换为python dict的最有效方法

时间:2018-11-09 16:22:31

标签: python regex string dictionary

如何转换字符串

{"key"=>"Number of Contents in Sales Package", "value"=>"Pack of 3"}

放入字典

{'Number of Contents in Sales Package':'Pack of 3'}?

4 个答案:

答案 0 :(得分:5)

您可以先使用str.replace然后使用ast.literal_eval将字符串转换为字典,然后进行重组:

from ast import literal_eval

x = '{"key"=>"Number of Contents in Sales Package", "value"=>"Pack of 3"}'

d = literal_eval(x.replace('=>', ':'))
d = {d['key']: d['value']}

print(d)

{'Number of Contents in Sales Package': 'Pack of 3'}

答案 1 :(得分:2)

re与一个包含多个键值对的示例一起使用

import re

s = """{"key"=>"Number of Contents in Sales Package", "value"=>"Pack of 3"}, 
    {"key"=>"Number of Contents in Sales Package 2", "value"=>"Pack of 5"}"""

pattern = re.compile(r'''{"key"=>"(?P<key>.*?)", "value"=>"(?P<value>.*?)"}''')
dict(pattern.findall(s))
{'Number of Contents in Sales Package': 'Pack of 3',
 'Number of Contents in Sales Package 2': 'Pack of 5'}

答案 2 :(得分:1)

您可以这样做:

result = dict([k_v.replace('"', '').split('=>')
               for k_v in string[1:-1].split(', ')])

这将要求您的数据采用以下格式:

'{key1=>value1, key2=>value2}'

答案 3 :(得分:0)

这是一种将字符串拆分和清理一点,然后对奇数和偶数列表元素(键为偶数,值为奇数)切片使用zip()的dict理解来生成输出的方法寻找(并且可以在包含多个键值对的字符串上使用,但是如果您的字符串包含嵌套的字典,列表等,效果会不太好。)

也就是说,@jpp的答案确实很聪明。

text = '{"key"=>"Number of Contents in Sales Package", "value"=>"Pack of 3"}'

items = [t.split('=>')[1].replace('"', '') for t in text[1:-1].split(',')]
result = {k: v for k, v in zip(items[::2], items[1::2])}

print(result)
# OUTPUT
# {'Number of Contents in Sales Package': 'Pack of 3'}