简体   繁体   English

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

[英]Nested list comprehension dict and list python

I have a list of dictionaries, which one with many keys and would like to filter only the value of the key price of each dictionary into a list. 我有一个字典列表,其中有很多键,并且只想将每个字典的键价格值过滤到一个列表中。 I was using the code below but not working... 我正在使用下面的代码,但无法正常工作...

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

Thanks in advance for any help! 在此先感谢您的帮助!

I think you need something like following (if data is your "list of dicts"): 我认为您需要以下内容(如果data是您的“词典列表”):

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

What I am doing is, iterating over list of dicts and to each dict use get('price') (as get() doesn't throw key exception) to read value of 'price' key. 我正在做的是,遍历字典列表,并对每个字典使用get('price') (因为get()不会抛出键异常)来读取'price'键的值。
Note: Avoid to use 'dict' as a variable name as it is in-build type name. 注意:避免使用“ dict”作为变量名称,因为它是内置类型名称。

Example: 例:

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

You can remove None in output list, by adding explicit if-check as: [d['price'] for d in data if 'price' in d] . 您可以通过以下方式添加显式的if-check来删除输出列表中的None[d['price'] for d in data if 'price' in d]

Reviews on your code: 您的代码的评论:

[b for a:b in dict.items() if a='price' for dict in data]
  1. You have silly syntax error a:b should be a, b 您有愚蠢的语法错误a:b应该是a, b
  2. Second, syntax error in if condition — a='price' should be a == 'price' (misspell == operator as =) 其次,if条件中的语法错误-a a='price'应该是a == 'price' (misspell ==运算符为=)
  3. Order of nested loops are wrong (in list compression we write nested loop later) 嵌套循环的顺序是错误的(在列表压缩中,我们稍后会编写嵌套循环)
  4. This is it not an error, it is but bad practice to use inbuilt type name as variable name. 这不是错误,使用内置类型名称作为变量名称是不好的做法。 You shouldn't use 'dict', 'list', 'str', etc as variable(or function) name. 您不应将“ dict”,“ list”,“ str”等用作变量(或函数)名称。

    Correct form of your code is: 您的代码的正确形式是:

      [b for dict in data for a, b in dict.items() if a == 'price' ] 
  5. In your list compression expression for a, b in dict.items() if a == 'price' loop is unnecessary—simple get(key) , setdefualt(key) or [key] works faster without loop. 在列表压缩表达式for a, b in dict.items() if a == 'price'不需要for a, b in dict.items() if a == 'price'循环,则for a, b in dict.items() if a == 'price'setdefualt(key)简单的get(key)setdefualt(key)[key]可以更快地进行无循环。

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

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