【问题标题】:Accessing elements of the dictionary in a loop in python在python的循环中访问字典的元素
【发布时间】:2019-02-03 15:02:08
【问题描述】:

我有一个数据集:

city_names_lst = 
  [{"cities":
     {"city":
         {"name":"New York",
          "population": "18mln",
          "suburbs": 
             {"s_name": "Brooklyn",
              "population":"9mln"},
             {"s_name": "Queens",
              "population": "9mln"}}},
     {"city":
         {"name":"Washington DC",
          "population":"10mln",
         "suburbs": 
             {"s_name": "Maryland",
              "population": "5mln"},
             {"s_name": "Northern Virginia",
              "population":"5mln"}}},
      ...}]

我需要遍历整个列表并访问“名称”键。

我的代码是:

city_names = []

for x in city_names_list:
    city_names = x['city']['name']

但是,它只获取第一个城市名称。 我如何获得所有这些?

【问题讨论】:

    标签: python python-3.x list dictionary iteration


    【解决方案1】:

    你很亲密。 追加到列表中,而不是重新分配其名称:

    city_names = []
    
    for x in city_names_list:
        city_names.append(x['city']['name'])
    

    我假设您的数据并非真的全部嵌套在“城市”键后面,就像在示例数据集中一样。

    【讨论】:

    • 谢谢,嵌套字典实际上更复杂——我调整了示例中的代码。
    猜你喜欢
    • 2023-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-07
    • 2016-01-05
    相关资源
    最近更新 更多