[英]Accessing elements of the dictionary in a loop in python
I have a dataset: 我有一个数据集:
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"}}},
...}]
I need to iterate through the entire list and access the "name" key. 我需要遍历整个列表并访问“name”键。
The code I have is: 我的代码是:
city_names = []
for x in city_names_list:
city_names = x['city']['name']
However, it only fetches the first city name. 但是,它只获取第一个城市名称。 How do I get all of them? 我如何获得所有这些?
You were close. 你很亲密 Append to the list, rather than reassigning its name: 附加到列表,而不是重新分配其名称:
city_names = []
for x in city_names_list:
city_names.append(x['city']['name'])
I'm assuming your data is not really all nested behind a "cities" key, like it is in the example dataset. 我假设您的数据并非全部嵌套在“城市”键后面,就像它在示例数据集中一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.