从字符串数据中提取嵌套dictionary〔PYTHON〕



我有一个字典data,它有一个关键字message,值为string

字典中的值是字符串+内部字典的组合。

我想把内部词典提取成一本单独的词典。

示例输入

data = {'message': '[INFO]-processed-result - {"customer_id": "cust_111","user_ids":[1,2,3],"collection":{"default":"def_1"}}'}

示例输出

output = {"customer_id": "cust_111","user_ids":[1,2,3],"collection":{"default":"def_1"}}

我不想使用python SPLIT

有人能提出解决方案吗

使用strindex方法和内置eval的另一种方法

>>> data = {'message': '[INFO]-processed-result-2020-10-01T23:45:49.472Z- {"customer_id": "cust_111","user_ids":[1,2,3],"collection":{"default":"def_1"}}'}
>>> index = data['message'].index('{')
>>> output = eval(data['message'][index:])
>>> output
{'customer_id': 'cust_111', 'user_ids': [1, 2, 3], 'collection': {'default': 'def_1'}}
>>>
>>> data = {'message': '[INFO]-processed-result - {"customer_id": "cust_111","user_ids":[1,2,3],"collection":{"default":"def_1"}}'}
>>> index = data['message'].index('{')
>>> output = eval(data['message'][index:])
>>> output
{'customer_id': 'cust_111', 'user_ids': [1, 2, 3], 'collection': {'default': 'def_1'}}

您也可以考虑使用json.loads()来获得更快的解决方案

>>> import json
>>> json.loads(data['message'][index:])
{'customer_id': 'cust_111', 'user_ids': [1, 2, 3], 'collection': {'default': 'def_1'}}

您可以简单地搜索第一个{,并使用索引来获取字典在字符串中的位置。

import ast
index_dict = data['message'].find('{')
output = ast.literal_eval(data['message'][index_dict:])

使用正则表达式:

import re
import ast
data = {'message': '[INFO]-processed-result - {"customer_id": "cust_111","user_ids":[1,2,3],"collection":{"default":"def_1"}}'}
output = {"customer_id": "cust_111","user_ids":[1,2,3],"collection":{"default":"def_1"}}
message = re.findall(r'^[INFO]-processed-result - (.*)', data['message']).pop()
output = ast.literal_eval(message)
print(output)

最新更新