简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM