[英]extract nested dictonary from String data[PYTHON]
我有一個字典data
,它有一個關鍵message
,值為string
。
字典中的值是字符串+內部字典的組合。
我想提取內部字典作為單獨的字典。
示例輸入
data = {'message': '[INFO]-processed-result - {"customer_id": "cust_111","user_ids":[1,2,3],"collection":{"default":"def_1"}}'}
Example_output
output = {"customer_id": "cust_111","user_ids":[1,2,3],"collection":{"default":"def_1"}}
我不想使用 python SPLIT
任何人都可以為此提出解決方案嗎?
您可以簡單地搜索第一個{
並使用索引來獲取字典在字符串中的位置。
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)
使用str
index
方法並使用內置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'}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.