我有这样的数据;
{"result": [{"name": "Mil", "age": 21, "id": 1}, {"name": "Jen", "age": 23, "id": 2}, {"name": "Rosa", "age": 26, "id": 3}]}
我如何才能从Python中这样的数据中只得到每个人的"年龄"值?
您可以访问以下年龄:
d = {"result": [{"name": "Mil", "age": 21, "id": 1}, {"name": "Jen", "age": 23, "id": 2}, {"name": "Rosa", "age": 26, "id": 3}]}
ages = [res["age"] for res in d["result"]] # [21, 23, 26]
事实上,d["result"]
是一个dicts列表。因此,在更扩展的形式中,它与相同
d = {"result": [{"name": "Mil", "age": 21, "id": 1}, {"name": "Jen", "age": 23, "id": 2}, {"name": "Rosa", "age": 26, "id": 3}]}
results = d["result"] # a list
ages = []
for res in results:
age = res["age"]
ages.append(age)
print(ages) # [21, 23, 26]
您可以使用以下代码:
dic={"result": [{"name": "Mil", "age": 21, "id": 1}, {"name": "Jen", "age": 23, "id": 2}, {"name": "Rosa", "age": 26, "id": 3}]}
lst = dic["result"]
age_lst =[]
for i in range(len(lst)):
age =lst[i]["age"]
age_lst = [age]+age_lst
print(age_lst)