Related
I have a list that looks like that:
[{'ip': 'x.x.x.x',
'error': True,
'reason': 'Reserved IP Address',
'reserved': True,
'version': 'IPv4'},
{'ip': 'x.x.x.x',
'error': True,
'reason': 'Reserved IP Address',
'reserved': True,
'version': 'IPv4'},
{'ip': 'x.x.x.x',
'version': 'IPv4',
'city': 'Munich',
'region': 'Bavaria',
'country': 'DE',
'country_name': 'Germany',
'country_code': 'DE',
'country_code_iso3': 'DEU',
'country_capital': 'Berlin'},
{'ip': 'x.x.x.x',
'version': 'IPv4',
'city': 'Düsseldorf',
'region': 'North Rhine-Westphalia',
'country': 'DE',
'country_name': 'Germany',
'country_code': 'DE',
'country_code_iso3': 'DEU',
'country_capital': 'Berlin'}]
What I need is a way to remove that elements than have an "error" or "reason : 'Reserved IP Address'" element inside and get only the elements that have complete data. Like this:
#Removing unnecesary elements
[{'ip': 'x.x.x.x',
'version': 'IPv4',
'city': 'Munich',
'region': 'Bavaria',
'country': 'DE',
'country_name': 'Germany',
'country_code': 'DE',
'country_code_iso3': 'DEU',
'country_capital': 'Berlin'},
{'ip': 'x.x.x.x',
'version': 'IPv4',
'city': 'Düsseldorf',
'region': 'North Rhine-Westphalia',
'country': 'DE',
'country_name': 'Germany',
'country_code': 'DE',
'country_code_iso3': 'DEU',
'country_capital': 'Berlin'}]
Is there any way to do that?
Try with list comprehension:
>>> [d for d in mylist if not d.get("error") and d.get("reason")!="Reserved IP Address"]
Another possible approach using the filter method, might be more flexible for more complex conditions
list_of_dict = [{'ip': 'x.x.x.x',
'error': True,
'reason': 'Reserved IP Address',
'reserved': True,
'version': 'IPv4'},
{'ip': 'x.x.x.x',
'error': True,
'reason': 'Reserved IP Address',
'reserved': True,
'version': 'IPv4'},
{'ip': 'x.x.x.x',
'version': 'IPv4',
'city': 'Munich',
'region': 'Bavaria',
'country': 'DE',
'country_name': 'Germany',
'country_code': 'DE',
'country_code_iso3': 'DEU',
'country_capital': 'Berlin'},
{'ip': 'x.x.x.x',
'version': 'IPv4',
'city': 'Düsseldorf',
'region': 'North Rhine-Westphalia',
'country': 'DE',
'country_name': 'Germany',
'country_code': 'DE',
'country_code_iso3': 'DEU',
'country_capital': 'Berlin'}]
def contains_error(dictionary):
return ('error' or 'reason') not in dictionary
result = list(filter(contains_error, list_of_dict))
print(result)
I'm using the Geocodio API to find congreessional district information for a given address. Here's my code:
from geocodio import GeocodioClient
import json
client = GeocodioClient('MY API KEY')
availible_offices = ['Congress', 'State Legislature']
# offices_dict = ['cd': "Congress",'stateleg': "State Legislature"]
location = str(client.geocode("100 Renaissance Center, Detroit, MI 48243",fields=["cd", "stateleg"]))
print(location)
json.loads(location)
Here's the json it prints:
{'input': {'address_components': {'number': '100', 'street': 'Renaissance', 'suffix': 'Ctr', 'formatted_street': 'Renaissance Ctr', 'city': 'Detroit', 'state': 'MI', 'zip': '48243', 'country': 'US'}, 'formatted_address': '100 Renaissance Ctr, Detroit, MI 48243'}, 'results': [{'address_components': {'number': '100', 'street': 'Renaissance', 'suffix': 'Ctr', 'formatted_street': 'Renaissance Ctr', 'city': 'Detroit', 'county': 'Wayne County', 'state': 'MI', 'zip': '48243', 'country': 'US'}, 'formatted_address': '100 Renaissance Ctr, Detroit, MI 48243', 'location': {'lat': 42.329033, 'lng': -83.039762}, 'accuracy': 1, 'accuracy_type': 'rooftop', 'source': 'Semcog', 'fields': {'congressional_districts': [{'name': 'Congressional District 14', 'district_number': 14, 'congress_number': '117th', 'congress_years': '2021-2023', 'proportion': 1, 'current_legislators': [{'type': 'representative', 'bio': {'last_name': 'Lawrence', 'first_name': 'Brenda', 'birthday': '1954-10-18', 'gender': 'F', 'party': 'Democrat'}, 'contact': {'url': 'https://lawrence.house.gov', 'address': '2463 Rayburn House Office Building Washington DC 20515-2214', 'phone': '202-225-5802', 'contact_form': None}, 'social': {'rss_url': None, 'twitter': 'RepLawrence', 'facebook': '395759603917487', 'youtube': None, 'youtube_id': 'UCf0USy9GNigkB8O9sS1dodw'}, 'references': {'bioguide_id': 'L000581', 'thomas_id': '02252', 'opensecrets_id': 'N00034068', 'lis_id': None, 'cspan_id': '79924', 'govtrack_id': '412638', 'votesmart_id': '78851', 'ballotpedia_id': 'Brenda Lawrence (Michigan)', 'washington_post_id': None, 'icpsr_id': '21530', 'wikipedia_id': 'Brenda Lawrence'}, 'source': 'Legislator data is originally collected and aggregated by https://github.com/unitedstates/'}, {'type': 'senator', 'bio': {'last_name': 'Stabenow', 'first_name': 'Debbie', 'birthday': '1950-04-29', 'gender': 'F', 'party': 'Democrat'}, 'contact': {'url': 'https://www.stabenow.senate.gov', 'address': '731 Hart Senate Office Building Washington DC 20510', 'phone': '202-224-4822', 'contact_form': 'https://www.stabenow.senate.gov/contact'}, 'social': {'rss_url': 'http://stabenow.senate.gov/rss/?p=news', 'twitter': 'SenStabenow', 'facebook': 'SenatorStabenow', 'youtube': 'senatorstabenow', 'youtube_id': 'UCFoDKCvxSwCUfDv-4Eg4K5A'}, 'references': {'bioguide_id': 'S000770', 'thomas_id': '01531', 'opensecrets_id': 'N00004118', 'lis_id': 'S284', 'cspan_id': '45451', 'govtrack_id': '300093', 'votesmart_id': '515', 'ballotpedia_id': 'Debbie Stabenow', 'washington_post_id': None, 'icpsr_id': '29732', 'wikipedia_id': 'Debbie Stabenow'}, 'source': 'Legislator data is originally collected and aggregated by https://github.com/unitedstates/'}, {'type': 'senator', 'bio': {'last_name': 'Peters', 'first_name': 'Gary', 'birthday': '1958-12-01', 'gender': 'M', 'party': 'Democrat'}, 'contact': {'url': 'https://www.peters.senate.gov', 'address': '724 Hart Senate Office Building Washington DC 20510', 'phone': '202-224-6221', 'contact_form': 'https://www.peters.senate.gov/contact/email-gary'}, 'social': {'rss_url': None, 'twitter': 'SenGaryPeters', 'facebook': 'SenGaryPeters', 'youtube': 'RepGaryPeters', 'youtube_id': 'UC7LYNbnKSK2VZqQ98YROWHQ'}, 'references': {'bioguide_id': 'P000595', 'thomas_id': '01929', 'opensecrets_id': 'N00029277', 'lis_id': 'S380', 'cspan_id': '50199', 'govtrack_id': '412305', 'votesmart_id': '8749', 'ballotpedia_id': 'Gary Peters', 'washington_post_id': None, 'icpsr_id': '20923', 'wikipedia_id': 'Gary Peters'}, 'source': 'Legislator data is originally collected and aggregated by https://github.com/unitedstates/'}]}], 'state_legislative_districts': {'house': {'name': 'State House District 6', 'district_number': '6', 'is_upcoming_state_legislative_district': False}, 'senate': {'name': 'State Senate District 1', 'district_number': '1', 'is_upcoming_state_legislative_district': False}}}}]}
Here's the error that I get:
Traceback (most recent call last):
File "/Users/aliallam/Desktop/APCSP/Create Task/Main.py", line 13, in <module>
json.loads(location)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
I want to extract certain parts of the json and print them. Why am I getting this error and how do I go about doing that?
Thanks in advance!
Use eval():
dataj = eval(location)
dataj.keys()
Output:
dict_keys(['input', 'results'])
I am using Python and I am trying to access the result of function PlacesAPI where I can see supermarkets around me and create a dataframe with few parts of each dictionary inside the main dictionary using a for loop, however I am getting the same information for different rows.
Can you please help me to put each different parts of dictionary in a different row?
Here is my code and the result (now reproducible):
from herepy import PlacesApi
import pandas as pd
def dataframe():
a = {'items': [{'title': 'Marcos Francisco dos Santos Padaria e Mercearia',
'id': 'here:pds:place:07675crc-dfd72cbf57bd45cc9277ed8530ffd61b',
'ontologyId': 'here:cm:ontology:supermarket',
'resultType': 'place',
'address': {'label': 'Marcos Francisco dos Santos Padaria e Mercearia, Rua Oswero Carmo Vilaça, 33, Petrópolis - RJ, 25635-101, Brazil',
'countryCode': 'BRA',
'countryName': 'Brazil',
'stateCode': 'RJ',
'state': 'Rio de Janeiro',
'city': 'Petrópolis',
'district': 'Petrópolis',
'street': 'Rua Oswero Carmo Vilaça',
'postalCode': '25635-101',
'houseNumber': '33'},
'position': {'lat': -22.5315, 'lng': -43.16904},
'access': [{'lat': -22.5314, 'lng': -43.16914}],
'distance': 134,
'categories': [{'id': '600-6300-0066', 'name': 'Grocery', 'primary': True},
{'id': '600-6300-0244', 'name': 'Bakery & Baked Goods Store'}],
'contacts': [{'phone': [{'value': '+552422312493'}]}]},
{'title': 'Mr. Frango',
'id': 'here:pds:place:076jx7ps-7c214f50052f0c23c9e5422ebde7d3cd',
'ontologyId': 'here:cm:ontology:supermarket',
'resultType': 'place',
'address': {'label': 'Mr. Frango, Rua Teresa, Petrópolis - RJ, 25635-530, Brazil',
'countryCode': 'BRA',
'countryName': 'Brazil',
'stateCode': 'RJ',
'state': 'Rio de Janeiro',
'city': 'Petrópolis',
'district': 'Petrópolis',
'street': 'Rua Teresa',
'postalCode': '25635-530'},
'position': {'lat': -22.52924, 'lng': -43.17222},
'access': [{'lat': -22.52925, 'lng': -43.1722}],
'distance': 545,
'categories': [{'id': '600-6300-0066', 'name': 'Grocery', 'primary': True},
{'id': '600-6000-0061', 'name': 'Convenience Store'}],
'references': [{'supplier': {'id': 'core'}, 'id': '1159487213'}],
'contacts': [{'phone': [{'value': '+552422201010'},
{'value': '+552422315720', 'categories': [{'id': '600-6000-0061'}]}]}]},
{'title': 'Mercadinho Flor de Petrópolis',
'id': 'here:pds:place:07675crc-6b03dfbac65a45c0bfc52ab9a3f04556',
'ontologyId': 'here:cm:ontology:supermarket',
'resultType': 'place',
'address': {'label': 'Mercadinho Flor de Petrópolis, Rua Teresa, 2060, Petrópolis - RJ, 25635-530, Brazil',
'countryCode': 'BRA',
'countryName': 'Brazil',
'stateCode': 'RJ',
'state': 'Rio de Janeiro',
'city': 'Petrópolis',
'district': 'Petrópolis',
'street': 'Rua Teresa',
'postalCode': '25635-530',
'houseNumber': '2060'},
'position': {'lat': -22.52895, 'lng': -43.17233},
'access': [{'lat': -22.52895, 'lng': -43.17219}],
'distance': 574,
'categories': [{'id': '600-6300-0066',
'name': 'Grocery',
'primary': True}]}]}
value = []
address = []
latlong = []
teste = pd.DataFrame(columns = ['nome','endereco','rua','numero',
'cidade','estado','cep','lat','long','raio'])
teste['nome'] = []
teste['endereco'] = []
teste['rua'] = []
teste['numero'] =[]
teste['cidade'] = []
teste['estado'] = []
teste['cep'] = []
teste['lat'] = []
teste['long'] = []
teste['raio'] = []
g = pd.DataFrame.from_dict(a.values())
h =[]
for i in range(3):
v = g[i].values[0]
h = v.items()
for k, l in h:
value.append(l)
for c, d in value[4].items():
address.append(d)
for la, lo in value[5].items():
latlong.append(lo)
novo_concorrente = {'nome': value[0], 'endereco':address[0],
'rua':address[7], 'numero':address[9],
'cidade':address[5], 'estado':address[3],
'cep':address[8],'lat':latlong[0],
'long':latlong[1],'raio':value[7]}
teste = teste.append(novo_concorrente, ignore_index=True)
return teste
You should focus on your for loop. I would suggest you to create a dictionary for each row you want to define in your final DataFrame, and then create a list to append those dictionaries to.
In example:
rows = []
for item in a["items"]:
row = {
"Latitude": item["position"]["lat"],
"Postal code": item["address"]["postalCode"],
}
rows.append(row)
result = DataFrame(rows)
result
Hope it helps as a starting point.
I'm a novice in Python and I'm having trouble with reading the API content and then looking in which dictionary and which list the information I want is in, etc. Is there an easier way than printing out elements down until you find the piece of data you want?
For example. I am trying to get to this element {'name': 'Famagusta District', 'lang': 'en'}
From this monstrosity:
{'address': 'Ammochostos', 'bbox': [33.548065185546875, 34.959442138671875, 34.590553283691406, 35.690277099609375], 'class_description': 'country, state, region,...', 'code': 'ADM1', 'confidence': 1, 'continent': 'EU', 'country': 'Cyprus', 'country_code': 'CY', 'country_geonames_id': '146669', 'description': 'first-order administrative division', 'dstOffset': 3, 'feature_class': 'A', 'geonames_id': 146615, 'lat': '35.33333', 'lng': '33.86667', 'ok': True, 'population': 46629, 'raw': {'timezone': {'gmtOffset': 2, 'timeZoneId': 'Asia/Famagusta', 'dstOffset': 3}, 'bbox': {'east': 34.590553283691406, 'south': 34.959442138671875, 'north': 35.690277099609375, 'west': 33.548065185546875, 'accuracyLevel': 0}, 'asciiName': 'Eparchia Ammochostou', 'astergdem': 133, 'countryId': '146669', 'fcl': 'A', 'srtm3': 134, 'countryCode': 'CY', 'adminCodes1': {'ISO3166_2': '04'}, 'adminId1': '146615', 'lat': '35.33333', 'fcode': 'ADM1', 'continentCode': 'EU', 'adminCode1': '01', 'lng': '33.86667', 'geonameId': 146615, 'toponymName': 'Eparchía Ammochóstou', 'adminTypeName': 'district', 'population': 46629, 'wikipediaURL': 'en.wikipedia.org/wiki/Famagusta_District', 'adminName5': '', 'adminName4': '', 'adminName3': '', 'alternateNames': [{'isPreferredName': True, 'name': '파마구스타 구', 'lang': 'ko'}, {'isShortName': True, 'isPreferredName': True, 'name': 'Ammochostos', 'lang': 'en'}, {'name': 'Ammóchostos', 'lang': 'el'}, {'name': 'Ammochostos District', 'lang': 'en'}, {'name': 'Eparchía Ammochóstou'}, {'name': 'Famagouste', 'lang': 'fr'}, {'isShortName': True, 'name': 'Famagusta', 'lang': 'en'}, {'name': 'Famagusta District', 'lang': 'en'}, {'name': 'Gazi Magosa İlçesi', 'lang': 'tr'}, {'name': 'Gazimağusa', 'lang': 'tr'}, {'name': 'https://en.wikipedia.org/wiki/Famagusta_District', 'lang': 'link'}, {'name': 'Magosa İlçesi', 'lang': 'tr'}, {'name': 'Q59148', 'lang': 'wkdt'}, {'name': 'Αμμόχωστος', 'lang': 'el'}, {'isPreferredName': True, 'name': 'Επαρχία Αμμοχώστου', 'lang': 'el'}], 'adminName2': '', 'name': 'Ammochostos', 'fclName': 'country, state, region,...', 'countryName': 'Cyprus', 'fcodeName': 'first-order administrative division', 'adminName1': 'Ammochostos'}, 'rawOffset': 2, 'srtm3': 134, 'state': 'Ammochostos', 'state_code': '01', 'state_geonames_id': '146615', 'status': 'OK', 'timeZoneId': 'Asia/Famagusta', 'timeZoneName': 'Asia/Famagusta', 'wikipedia': 'en.wikipedia.org/wiki/Famagusta_District'}
So Far I went so already 3 levels down but 4th layer seems to have at least dozen elements and AlternateNames is not one of them so it's at least 1 more level down.
print(row['features'][0]['properties'])
I am using Pycharm. Is there any way to view this with indentation or search function? If not what is the easiest way to read the elements down?
I'm not sure what name you have given to your dictionary. I have copied the text above and assigned it to a dictionary called 'dict1' for the purposes of showing you this answer.
dict1 = {'address': 'Ammochostos', 'bbox': [33.548065185546875, 34.959442138671875, 34.590553283691406, 35.690277099609375], 'class_description': 'country, state, region,...', 'code': 'ADM1', 'confidence': 1, 'continent': 'EU', 'country': 'Cyprus', 'country_code': 'CY', 'country_geonames_id': '146669', 'description': 'first-order administrative division', 'dstOffset': 3, 'feature_class': 'A', 'geonames_id': 146615, 'lat': '35.33333', 'lng': '33.86667', 'ok': True, 'population': 46629, 'raw': {'timezone': {'gmtOffset': 2, 'timeZoneId': 'Asia/Famagusta', 'dstOffset': 3}, 'bbox': {'east': 34.590553283691406, 'south': 34.959442138671875, 'north': 35.690277099609375, 'west': 33.548065185546875, 'accuracyLevel': 0}, 'asciiName': 'Eparchia Ammochostou', 'astergdem': 133, 'countryId': '146669', 'fcl': 'A', 'srtm3': 134, 'countryCode': 'CY', 'adminCodes1': {'ISO3166_2': '04'}, 'adminId1': '146615', 'lat': '35.33333', 'fcode': 'ADM1', 'continentCode': 'EU', 'adminCode1': '01', 'lng': '33.86667', 'geonameId': 146615, 'toponymName': 'Eparchía Ammochóstou', 'adminTypeName': 'district', 'population': 46629, 'wikipediaURL': 'en.wikipedia.org/wiki/Famagusta_District', 'adminName5': '', 'adminName4': '', 'adminName3': '', 'alternateNames': [{'isPreferredName': True, 'name': '파마구스타 구', 'lang': 'ko'}, {'isShortName': True, 'isPreferredName': True, 'name': 'Ammochostos', 'lang': 'en'}, {'name': 'Ammóchostos', 'lang': 'el'}, {'name': 'Ammochostos District', 'lang': 'en'}, {'name': 'Eparchía Ammochóstou'}, {'name': 'Famagouste', 'lang': 'fr'}, {'isShortName': True, 'name': 'Famagusta', 'lang': 'en'}, {'name': 'Famagusta District', 'lang': 'en'}, {'name': 'Gazi Magosa İlçesi', 'lang': 'tr'}, {'name': 'Gazimağusa', 'lang': 'tr'}, {'name': 'https://en.wikipedia.org/wiki/Famagusta_District', 'lang': 'link'}, {'name': 'Magosa İlçesi', 'lang': 'tr'}, {'name': 'Q59148', 'lang': 'wkdt'}, {'name': 'Αμμόχωστος', 'lang': 'el'}, {'isPreferredName': True, 'name': 'Επαρχία Αμμοχώστου', 'lang': 'el'}], 'adminName2': '', 'name': 'Ammochostos', 'fclName': 'country, state, region,...', 'countryName': 'Cyprus', 'fcodeName': 'first-order administrative division', 'adminName1': 'Ammochostos'}, 'rawOffset': 2, 'srtm3': 134, 'state': 'Ammochostos', 'state_code': '01', 'state_geonames_id': '146615', 'status': 'OK', 'timeZoneId': 'Asia/Famagusta', 'timeZoneName': 'Asia/Famagusta', 'wikipedia': 'en.wikipedia.org/wiki/Famagusta_District'}
Running dict1 alone will allow you to view how this looks in a much neater way. (I'm using Google Colab)
If I then run this line, it returns the data you are interested in:
dict1['raw']['alternateNames'][7]
This works because you must return the elements within the outer dictionary, and inner dictionaries. Once you reach 'alternateNames', you can find the information you want using list indexing.
fork_fig = {'categories': [{'alias': 'burgers', 'title': 'Burgers'},
{'alias': 'sandwiches', 'title': 'Sandwiches'},
{'alias': 'salad', 'title': 'Salad'}],
'coordinates': {'latitude': 35.10871, 'longitude': -106.56739},
'display_phone': '(505) 881-5293',
'distance': 3571.724649307866,
'id': 'fork-and-fig-albuquerque',
'image_url': 'https://s3-media1.fl.yelpcdn.com/bphoto/_-DpXKfS3jv6DyA47g6Fxg/o.jpg',
'is_closed': False,
'location': {'address1': '6904 Menaul Blvd NE',
'address2': 'Ste C',
'address3': '',
'city': 'Albuquerque',
'country': 'US',
'display_address': ['6904 Menaul Blvd NE', 'Ste C', 'Albuquerque, NM 87110'],
'state': 'NM',
'zip_code': '87110'},
'name': 'Fork & Fig',
'phone': '+15058815293',
'price': '$$',
'rating': 4.5,
'review_count': 604}
frontier_restaurant = {'categories': [{'alias': 'mexican', 'title': 'Mexican'},
{'alias': 'diners', 'title': 'Diners'},
{'alias': 'tradamerican', 'title': 'American (Traditional)'}],
'coordinates': {'latitude': 35.0808088832532, 'longitude': -106.619402244687},
'display_phone': '(505) 266-0550',
'distance': 4033.6583235266075,
'id': 'frontier-restaurant-albuquerque-2',
'image_url': 'https://s3-media4.fl.yelpcdn.com/bphoto/M9L2z6-G0NobuDJ6YTh6VA/o.jpg',
'is_closed': True,
'location': {'address1': '2400 Central Ave SE',
'address2': '',
'address3': '',
'city': 'Albuquerque',
'country': 'US',
'display_address': ['2400 Central Ave SE', 'Albuquerque, NM 87106'],
'state': 'NM',
'zip_code': '87106'},
'name': 'Frontier Restaurant',
'phone': '+15052660550',
'price': '$',
'rating': 4.0,
'review_count': 1369}
I have two restaurant list as above and i want to make function that returns a list of only the restaurants that are not closed by using conditional loops.
restaurants = [fork_fig, frontier_restaurant]
open_restaurants(restaurants)[0]['name'] ###I want restaurant name to be appear
Below is the code that I've been working on and cannot quite sure how I can fix this to get the value that I want to return.
def open_restaurants(restaurants):
selected = []
for i in restaurants:
if fork_fig['is_closed']:
selected = restaurants[1]
else:
selected = restaurants[0]
return selected
Continuing from the comment:
fork_fig = {'categories': [{'alias': 'burgers', 'title': 'Burgers'},
{'alias': 'sandwiches', 'title': 'Sandwiches'},
{'alias': 'salad', 'title': 'Salad'}],
'coordinates': {'latitude': 35.10871, 'longitude': -106.56739},
'display_phone': '(505) 881-5293',
'distance': 3571.724649307866,
'id': 'fork-and-fig-albuquerque',
'image_url': 'https://s3-media1.fl.yelpcdn.com/bphoto/_-DpXKfS3jv6DyA47g6Fxg/o.jpg',
'is_closed': False,
'location': {'address1': '6904 Menaul Blvd NE',
'address2': 'Ste C',
'address3': '',
'city': 'Albuquerque',
'country': 'US',
'display_address': ['6904 Menaul Blvd NE', 'Ste C', 'Albuquerque, NM 87110'],
'state': 'NM',
'zip_code': '87110'},
'name': 'Fork & Fig',
'phone': '+15058815293',
'price': '$$',
'rating': 4.5,
'review_count': 604}
frontier_restaurant = {'categories': [{'alias': 'mexican', 'title': 'Mexican'},
{'alias': 'diners', 'title': 'Diners'},
{'alias': 'tradamerican', 'title': 'American (Traditional)'}],
'coordinates': {'latitude': 35.0808088832532, 'longitude': -106.619402244687},
'display_phone': '(505) 266-0550',
'distance': 4033.6583235266075,
'id': 'frontier-restaurant-albuquerque-2',
'image_url': 'https://s3-media4.fl.yelpcdn.com/bphoto/M9L2z6-G0NobuDJ6YTh6VA/o.jpg',
'is_closed': True,
'location': {'address1': '2400 Central Ave SE',
'address2': '',
'address3': '',
'city': 'Albuquerque',
'country': 'US',
'display_address': ['2400 Central Ave SE', 'Albuquerque, NM 87106'],
'state': 'NM',
'zip_code': '87106'},
'name': 'Frontier Restaurant',
'phone': '+15052660550',
'price': '$',
'rating': 4.0,
'review_count': 1369}
restaurants = [fork_fig, frontier_restaurant]
def open_restaurants(restaurants):
selected = []
for i in restaurants:
if 'is_closed' in i:
if not i['is_closed']:
selected.append(i['name'])
return selected
print(open_restaurants(restaurants))
OUTPUT:
['Fork & Fig']
Shorter-version:
Using list-comprehension:
def open_restaurants(restaurants):
return [x['name'] for x in restaurants if 'is_closed' in x and not x["is_closed"]]
print(open_restaurants(restaurants))
Using get() instead of indexing:
def open_restaurants(restaurants):
return [x['name'] for x in restaurants if 'name' in x and not x.get('is_closed', True)]
print(open_restaurants(restaurants))
Use the filter function:
def open_restaurants(restaurants):
return filter(lambda r: not r['is_closed'], restaurants)
Use List Comprehension here. Its one line and easy to read
open_restaurants = [restaurant.get("name") for restaurant in restaurants if not restaurant.get("is_closed")]
Output: ["Fork & Fig"]
There is a simple way to append all your open restaurants to a new list and print their names.
You will need two loops to accomplish this.
Here is how to do it:
restaurants = [fork_fig, frontier_restaurant] # a list of restaurants
def open_restaurants(restaurants):
selected = []
for i in restaurants: # append all open restaurants to a new list
if not i['is_closed']:
selected.append(i)
return selected
my_open_restaurants = open_restaurants(restaurants) # call the function
for rest in my_open_restaurants: # print all the names
print(rest['name'])
In your example the output will be: Fork & Fig