从字符串数据中提取嵌套字典。[PYTHON]

时间:2020-10-02 06:06:26

标签: python python-3.x

我有一个字典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

有人可以为此建议解决方案吗?

3 个答案:

答案 0 :(得分:1)

您可以简单地搜索第一个import ast index_dict = data['message'].find('{') output = ast.literal_eval(data['message'][index_dict:]) 并使用索引来获取字典在字符串中的位置。

import operator
mylist =[(0,3),(2,6),(1,10)]

def accumulate(L, i, op):
  def iter(result, rest, out):
    if rest == []:
      return out
    else:
      r = op(result, rest[0][i-1])
      return iter(r, rest[1:], out + [r])
  return iter(L[0][i-1], L[1:], [])

print(accumulate(mylist, 2, operator.add))
print(accumulate(mylist, 1, operator.add))
print(accumulate(mylist, 2, operator.mul))

# ==>
# [9, 19]
# [2, 3]
# [18, 180]

答案 1 :(得分:1)

使用正则表达式:

<RemoteAuthenticatorView Action="@Action" OnLogOutSucceeded="LogoutSucceeded">
</RemoteAuthenticatorView>

@code{
    [Parameter] public string Action { get; set; }

    private async Task LogoutSucceeded()
    {
        await JsInterop.InvokeVoidAsync("alert", "You have been logged out due to inactivity.");
    }
}

答案 2 :(得分:1)

使用index的{​​{1}}方法并使用内置str

的另一种方法
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()