简体   繁体   中英

convert a string of list into a list

In python3, Can you please help convert the dictionary values that is a long string into a list:

d1 = 
{'result': '[{"pod_name": "kafka-9", "resolution_ms": 60000, "value": 420.85}, 
{"pod_name": "kafka-3", "resolution_ms": 60000, "value": 418.0}]'...}

The dict values is a string, not a list as it should be, how can I conver the dictionary into a list like

res = 
{'result': [{"pod_name": "kafka-9", "resolution_ms": 60000, "value": 420.85}, 
{"pod_name": "kafka-3", "resolution_ms": 60000, "value": 418.0}]...}

Try this; using json

import json
df1 = {'result': '[{"pod_name": "kafka-9", "resolution_ms": 60000, "value": 420.85},{"pod_name": "kafka-3", "resolution_ms": 60000, "value": 418.0}]'}
result = [json.loads(idx.replace("'", '"')) for idx in [df1['result']]]
df1['result'] = result[0]

# Output of df1;
{'result': [{'pod_name': 'kafka-9', 'resolution_ms': 60000, 'value': 420.85},
            {'pod_name': 'kafka-3', 'resolution_ms': 60000, 'value': 418.0}]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM