python - 在python中循环访问字典的元素

标签 python python-3.x list dictionary iteration

我有一个数据集:

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"}}},
      ...}]

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

我的代码是:

city_names = []

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

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

最佳答案

你很接近。 附加到列表,而不是重新分配其名称:

city_names = []

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

我假设您的数据并不真正全部嵌套在“cities”键后面,就像在示例数据集中那样。

关于python - 在python中循环访问字典的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52067004/

相关文章:

python-3.x - Python 中 Matplotlib 中的响应式文本

python - 如何迭代数据框列

Linux, python 3 : syntax error on commandline but not in ipython %run command

.net - 什么时候分配新列表比 .Clear() 现有列表更合适?

c# - 如何查看存储在列表中的值?

未调用 Python 析构函数

python - 在 Windows 10 VS2015 上使用 Python 和 GPU 支持构建和编译 OpenCV

python - 在 Python 中向列表添加额外元素的有效方法

python - 函数和 if - else 在 python 中。多个条件。代码学院

python - 'tensorflow_core.estimator' 没有属性 'inputs' ,为什么会发生这种情况?