将字符串转换为数组或字典列表
Convert string into array or list of dicts
我是 运行 一个 API 调用,它给出下一个字符串作为输出:
"[{'hour':'5', 'day':'11', 'month':'sep', 'year':'2019'}, {'user_id':'x651242w', 'session_id':4025, 'location':'USA'}]"
我想访问位置,在这种情况下我应该怎么做?
我正在考虑将字符串转换为字典数组或字典列表?
s = "[{'hour':'5', 'day':'11', 'month':'sep', 'year':'2019'}, {'user_id':'x651242w', 'session_id':4025, 'location':'USA'}]"
res = list(eval(s))
print(res[1]["location"])
'USA'
import ast
s = "[{'hour':'5', 'day':'11', 'month':'sep', 'year':'2019'}, {'user_id':'x651242w', 'session_id':4025, 'location':'USA'}]"
lst = ast.literal_eval(s)
print(lst)
# [{'hour': '5', 'day': '11', 'month': 'sep', 'year': '2019'}, {'user_id': 'x651242w', 'session_id': 4025, 'location': 'USA'}]
print(lst[1]['location'])
# USA
假设您不知道哪个词典包含位置键。这也可能会给您一些更一般的想法:
from ast import literal_eval
s = "[{'hour':'5', 'day':'11', 'month':'sep', 'year':'2019'}, {'user_id':'x651242w', 'session_id':4025, 'location':'USA'}]"
for dict_ in literal_eval(s):
if location := dict_.get('location'):
print(location)
输出:
USA
这看起来 json,对于 json ,我们必须将单引号更改为双引号,然后您可以解析 json:
str1 = "[{'hour':'5', 'day':'11', 'month':'sep', 'year':'2019'},
{'user_id':'x651242w', 'session_id':4025, 'location':'USA'}]"
json_str = str1.replace("'", '"')
json_format = json.loads(a)
json_format[1]["location"]
我是 运行 一个 API 调用,它给出下一个字符串作为输出:
"[{'hour':'5', 'day':'11', 'month':'sep', 'year':'2019'}, {'user_id':'x651242w', 'session_id':4025, 'location':'USA'}]"
我想访问位置,在这种情况下我应该怎么做?
我正在考虑将字符串转换为字典数组或字典列表?
s = "[{'hour':'5', 'day':'11', 'month':'sep', 'year':'2019'}, {'user_id':'x651242w', 'session_id':4025, 'location':'USA'}]"
res = list(eval(s))
print(res[1]["location"])
'USA'
import ast
s = "[{'hour':'5', 'day':'11', 'month':'sep', 'year':'2019'}, {'user_id':'x651242w', 'session_id':4025, 'location':'USA'}]"
lst = ast.literal_eval(s)
print(lst)
# [{'hour': '5', 'day': '11', 'month': 'sep', 'year': '2019'}, {'user_id': 'x651242w', 'session_id': 4025, 'location': 'USA'}]
print(lst[1]['location'])
# USA
假设您不知道哪个词典包含位置键。这也可能会给您一些更一般的想法:
from ast import literal_eval
s = "[{'hour':'5', 'day':'11', 'month':'sep', 'year':'2019'}, {'user_id':'x651242w', 'session_id':4025, 'location':'USA'}]"
for dict_ in literal_eval(s):
if location := dict_.get('location'):
print(location)
输出:
USA
这看起来 json,对于 json ,我们必须将单引号更改为双引号,然后您可以解析 json:
str1 = "[{'hour':'5', 'day':'11', 'month':'sep', 'year':'2019'},
{'user_id':'x651242w', 'session_id':4025, 'location':'USA'}]"
json_str = str1.replace("'", '"')
json_format = json.loads(a)
json_format[1]["location"]