简体   繁体   中英

how to sort values from a dictionary in a list

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.

.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.

Try this:

for visits in geo_logs:
  for visit,[City,Country] in visits.items():
    if Country == 'India':
      print (visits)

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