I'm trying to extract the city names out of the below dictionary/list and create a new list just of the city names. So the new list would look like this: cities = ["Paris","Berlin","Tokyo","Sydney"]
I can't even figure out it I need to do this with list comprehension or dictionary comprehension.
cities_response_data = {
"prices": [
{
"city": "Paris",
"iataCode": "",
"lowestPrice": 54,
"id": 2
},
{
"city": "Berlin",
"iataCode": "",
"lowestPrice": 42,
"id": 3
},
{
"city": "Tokyo",
"iataCode": "",
"lowestPrice": 485,
"id": 4
},
{
"city": "Sydney",
"iataCode": "",
"lowestPrice": 551,
"id": 5
},
]
}
If you could try to explain how the code works as well as what it actually is that would be amazing. I know I'm missing something fundamental here..
These are some of the attempts that haven't worked: cities = [city for city in cities_response_data["prices"][0]["city"]]
- result: ['P', 'a', 'r', 'i', 's']
cities = [value for (key,value) in cities_response_data["prices"][0]["city"]]
- result: ValueError: not enough values to unpack (expected 2, got 1)
cities = [value for (key,value) in cities_response_data["prices"][0].items()]
- result: ['Paris', '', 54, 2]
cities = {city for city in cities_response_data["prices"][0]}
- result: {'lowestPrice', 'id', 'iataCode', 'city'}
cities = {city for city in cities_response_data["prices"][0]["city"].items()}
- result: AttributeError: 'str' object has no attribute 'items'
cities = {city for city in cities_response_data["prices"][0]["city"].iterows}
- result - AttributeError: 'str' object has no attribute 'iterows'
Does it needed to be nested, something like this: cities = [value for value in ["".join([value for value in cities_response_data["prices"][0]["city"]])]]
- result: ['Paris']