嵌套列表理解字典和列表python

时间:2014-04-21 08:02:03

标签: python list dictionary

我有一个词典列表,其中一个词典有许多键,并且只想将每个词典的键价值过滤到列表中。我使用下面的代码但没有工作......

print [b for a:b in dict.items() if a='price' for dict in data]

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:5)

我认为您需要以下内容(如果data是您的“词典列表”):

[d.get('price') for d in data]

我正在做的是,迭代dicts列表和每个dict使用get('price')(因为get()不会抛出关键异常)来读取'price'键的值。
注意:避免使用'dict'作为变量名,因为它是构建内类型名称。

示例:

>>> data = [ {'price': 2, 'b': 20}, 
             {'price': 4, 'a': 20}, 
             {'c': 20}, {'price': 6, 'r': 20} ]  # indented by hand
>>> [d.get('price') for d in data]
[2, 4, None, 6]
>>> 

您可以删除输出列表中的None,方法是将明确的if-check添加为:[d['price'] for d in data if 'price' in d]

对代码的评论:

[b for a:b in dict.items() if a='price' for dict in data]
  1. 你有愚蠢的语法错误a:b应该是a, b
  2. 其次,if条件中的语法错误 - a='price'应为a == 'price'(misspell == operator as =)
  3. 嵌套循环的顺序是错误的(在列表压缩中我们稍后编写嵌套循环)
  4. 这不是错误,使用内置类型名称作为变量名称是不好的做法。你不应该使用'dict','list','str'等作为变量(或函数)名称。

    正确的代码形式是:

     [b for dict in data for a, b in dict.items() if a == 'price' ]
    
  5. 在您的列表中,压缩表达式for a, b in dict.items() if a == 'price'循环是不必要的 - 简单get(key)setdefualt(key)[key]无需循环即可更快地运行。
相关问题