gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:42:50 24 4
gpt4 key购买 nike

我有一个数据集:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com