[英]Iterate through list of dictionaries in Python and return value
I have a list of dictionaries in this format:我有一个这种格式的字典列表:
user_input =[{
'user':'guest',
'record':
'{"message":"User Request","context":{"session_id":"YWOZe"},"level":100}'
},
{
'user':'guest',
'record':
'{"message":"User Inquiry","context":{"session_id":"YWOZf"},"level":100}'
},
]
What I want is, I want to use eval in eval(user_input[0]['record']) and eval(user_input[1]['record']) by iterating over two dictionaries, so far I could do for one dictionary as我想要的是,我想通过迭代两个字典在 eval(user_input[0]['record']) 和 eval(user_input[1]['record']) 中使用 eval,到目前为止我可以为一个字典做作为
def record_to_objects(data:dict):
new_dict = {}
for key, value in data.items():
if data[key] == data['record']:
new_dict['record'] = eval(data['record'])
r = data
del r['record']
return {**r, **new_dict}
But for two dictionaries in a list, I got only one result(as the last item) using "double for loop", maybe I am not returning in a proper way.但是对于列表中的两个字典,我使用“double for loop”只得到一个结果(作为最后一项),也许我没有以正确的方式返回。 Expected output:
预期输出:
output = [
{'user': 'guest',
'record': {'message': 'User Request',
'context': {'session_id': 'YWOZe'},
'level': 100}},
{'user': 'guest',
'record': {'message': 'User Inquiry',
'context': {'session_id': 'YWOZf'},
'level': 100}}
]
Can somebody help me?有人可以帮助我吗? I want a list of dictionaries and both should have been processed by the eval method.
我想要一个字典列表,两者都应该由 eval 方法处理。
That looks like JSON.这看起来像 JSON。 You should not use
eval()
for this .您不应为此使用
eval()
。 Instead, use json.loads()
with a for
loop:相反,将
json.loads()
与for
循环一起使用:
import json
for item in user_input:
item["record"] = json.loads(item["record"])
This outputs:这输出:
[
{
'user': 'guest',
'record': {'message': 'User Request', 'context': {'session_id': 'YWOZe'}, 'level': 100}
},
{
'user': 'guest',
'record': {'message': 'User Inquiry', 'context': {'session_id': 'YWOZf'}, 'level': 100}
}
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.