我有这些列表,我想获取名称的值:
[{
"tr": [{
"name": "#For5Rs",
"promoted_content": null,
"query": "%23For5Rs",
"events": null
}, {
"name": "Javed Bashir",
"promoted_content": null,
"query": "%22Javed+Bashir%22",
"events": null
}, {
"name": "Milan Luthria",
"promoted_content": null,
"query": "%22Milan+Luthria%22",
"events": null
}, {
"name": "Vidya Balan",
"promoted_content": null,
"query": "%22Vidya+Balan%22",
"events": null
}],
"as_of": "2013-08-16T10:31:35Z",
"created_at": "2013-08-16T10:20:41Z",
"locations": [{
"name": "India",
"woeid": 23424848
}]
}]
for element in data['tr']:
print element['name']
print element['promoted_content']
print element['query']
print element['events']
您在问:“我有一个字典列表。每个字典都有一个键
"name"
。我如何获取所有这些键的值列表?”
使用括号中的索引访问列表元素。
a[0]
是列表的第一个元素。使用括号中的键访问字典值。
a["name"]
是 this_value
来自 {"name":this_value}
。使用循环聚合值,如下所示:
aggregator = []
for item in a_list:
aggregator.append(value_calculated_from(item))
your_list
没有配对的方括号。
我想
outer_dictionary = your_list[0]
list_of_dictionaries = outer_dictionary['tr']
可以获取“name”的值列表:
names = []
for dictionary in list_of_dictionaries:
if "name" in dictionary:
names.append(dictionary["name"])
我看到你的数据没有完全格式化(在编辑之前) - 所以我会使用正则表达式 - 下面的代码从提供的 json 中提取所有名称STRING(只需包含“”“”“”)
import re
data="""[{
"tr": [{
"name": "#For5Rs",
"promoted_content": null,
"query": "%23For5Rs",
"events": null
}, {
"name": "Javed Bashir",
"promoted_content": null,
"query": "%22Javed+Bashir%22",
"events": null
}, {
"name": "Milan Luthria",
"promoted_content": null,
"query": "%22Milan+Luthria%22",
"events": null
}, {
"name": "Vidya Balan",
"promoted_content": null,
"query": "%22Vidya+Balan%22",
"events": null
}],
"as_of": "2013-08-16T10:31:35Z",
"created_at": "2013-08-16T10:20:41Z",
"locations": [{
"name": "India",
"woeid": 23424848
}]
"""
names=re.findall(r'(?<="name":\s").+(?=",[\s\S]+"promoted_content")',data)
print names
它打印一个列表-
['#For5Rs', 'Javed Bashir', 'Milan Luthria', 'Vidya Balan']
试试这个
for element in data[key]:
#print your values here
这将为您提供姓名列表
new_list = [x['name'] for x in data['tr']]