如何使用字典中的特定键访问每个元素

时间:2020-07-14 19:40:52

标签: python api dictionary

我正在从API中提取数据,结果看起来像这样:

textContent

我想用键“ geoid”(这些是邮政编码)仅提取元素的列表。如何遍历列表以提取这些元素?

2 个答案:

答案 0 :(得分:2)

您可以通过将dictionary命名为变量a,然后在[]括号之间进行调用来实现。对于您的dictionary和所需的输出,它看起来像这样:

a = {
  "data": {
    "year": "2020",
    "quarter": "1",
    "input": "31080",
    "crosswalk_type": "cbsa-zip",
    "results": [
      {
        "geoid": "90250",
        "res_ratio": 0.006727469865159593,
        "bus_ratio": 0.003776624306425631,
        "oth_ratio": 0.013730729472865928,
        "tot_ratio": 0.006843653586843295
      },
      {
        "geoid": "90046",
        "res_ratio": 0.00655721932565345,
        "bus_ratio": 0.0033795987438371543,
        "oth_ratio": 0.008322582982031358,
        "tot_ratio": 0.006338246981004679
      },
      {
        "geoid": "90025",
        "res_ratio": 0.005284695525716839,
        "bus_ratio": 0.006336137461965276,
        "oth_ratio": 0.0112871723000365,
        "tot_ratio": 0.005749518826354573
      },
      {
        "geoid": "90509",
        "res_ratio": 0,
        "bus_ratio": 0,
        "oth_ratio": 0.000002786268156019872,
        "tot_ratio": 1.6597918089938143e-7
      }
    ]
  }
}

geoids = [x['geoid'] for x in a['data']['results']]

答案 1 :(得分:1)

data = {
    "data": {
        "year": "2020",
        "quarter": "1", 
        ...

geoids = [code['geoid'] for code in data['data']['results']]