Reputation: 33
I'm just starting to learn python. We were told about data types (integer, float, boolean), and also about sets, strings, lists etc. A little more about cycles (for/while). In my homework I need code which returns a filtered list of geo_logs containing only visits from India.
I need to do this without difficult functions, alpha or something like that. Only standard cycles.
geo_logs = [
{'visit1': ['Moscow', 'Russia']},
{'visit2': ['Delhi', 'India']},
{'visit3': ['Bangalore', 'India']},
{'visit4': ['Lisbon', 'Portugal']},
{'visit5': ['Paris', 'France']},
{'visit6': ['Mumbai', 'India']},
]
for visit in geo_logs:
if visit.values() == 'India':
print(visit.values())
but this does not return anything.
If possible, write a code and explain it. I want to understand how python works, and not just do homework.
Upvotes: 1
Views: 85
Reputation: 1810
Try this:
for visits in geo_logs:
for visit,[City,Country] in visits.items():
if Country == 'India':
print (visits)
Upvotes: 1
Reputation: 33359
.values()
returns a list of all the values in the entire dictionary. Since your values are already a list, now you have a list-of-list, like [['Delhi', 'India']]
Obviously, [['Delhi', 'India']]
does not equal 'India'
.
Try if 'India' in list(visit.values())[0]
instead.
This data structure is a bit confusing -- why do you have different keys visit1
, visit2
etc. when the data is in separate dictionaries anyway? Either make them all have the same key visit
, or combine them into one large dictionary.
Upvotes: 1