如何使用Python从JSON获取单个键的值列表

问题描述 投票:0回答:5

我有这些列表,我想获取名称的值:

[{
  "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
  }]
}]
python json variables select fetch
5个回答
7
投票
for element in data['tr']:
    print element['name']
    print element['promoted_content']
    print element['query']
    print element['events']

6
投票

您在问:“我有一个字典列表。每个字典都有一个键

"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"])

2
投票

我看到你的数据没有完全格式化(在编辑之前) - 所以我会使用正则表达式 - 下面的代码从提供的 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']

1
投票

试试这个

for element in data[key]:
   #print your values here

0
投票

这将为您提供姓名列表

new_list = [x['name'] for x in data['tr']]
© www.soinside.com 2019 - 2024. All rights reserved.