简体   繁体   English

如何对列表中的字典中的值进行排序

[英]how to sort values from a dictionary in a list

I'm just starting to learn python. 我刚刚开始学习python。 We were told about data types (integer, float, boolean), and also about sets, strings, lists etc. A little more about cycles (for/while). 我们被告知有关数据类型(整数,浮点数,布尔值),以及集合,字符串,列表等的信息。关于循环的更多信息(for / while)。 In my homework I need code which returns a filtered list of geo_logs containing only visits from India. 在我的作业中,我需要代码返回仅包含来自印度的访问的geo_logs过滤列表。

I need to do this without difficult functions, alpha or something like that. 我需要没有困难的功能,alpha或类似的东西来执行此操作。 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. 我想了解python的工作原理,而不仅仅是做家庭作业。

.values() returns a list of all the values in the entire dictionary. .values()返回整个字典中所有值的列表。 Since your values are already a list, now you have a list-of-list, like [['Delhi', 'India']] 由于您的值已经是一个列表,所以现在您有了一个列表列表,例如[['Delhi', 'India']]

Obviously, [['Delhi', 'India']] does not equal 'India' . 显然, [['Delhi', 'India']]不等于'India'

Try if 'India' in list(visit.values())[0] instead. 尝试if 'India' in list(visit.values())[0]

This data structure is a bit confusing -- why do you have different keys visit1 , visit2 etc. when the data is in separate dictionaries anyway? 这个数据结构有点令人困惑-当数据仍然位于单独的词典中时,为什么您具有不同的键visit1visit2等? Either make them all have the same key visit , or combine them into one large dictionary. 要么使它们都具有相同的键visit ,要么将它们组合成一本大词典。

Try this: 尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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