简体   繁体   中英

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"):

[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.
Note: Avoid to use 'dict' as a variable name as it is in-build type name.

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

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
  2. Second, syntax error in if condition — a='price' should be a == 'price' (misspell == operator as =)
  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.

    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.

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