Python list comprehension for dictionaries in dictionaries?

Viewed 60988

I just learned about list comprehension, which is a great fast way to get data in a single line of code. But something's bugging me.

In my test I have this kind of dictionaries inside the list:

[{'y': 72, 'x': 94, 'fname': 'test1420'}, {'y': 72, 'x': 94, 'fname': 'test277'}]

The list comprehension s = [ r for r in list if r['x'] > 92 and r['x'] < 95 and r['y'] > 70 and r['y'] < 75 ] works perfectly on that (it is, in fact, the result of this line)

Anyway, I then realised I'm not really using a list in my other project, I'm using a dictionary. Like so:

{'test1420': {'y': '060', 'x': '070', 'fname': 'test1420'}}

That way I can simply edit my dictionary with var['test1420'] = ...

But list comprehensions don't work on that! And I can't edit lists this way because you can't assign an index like that.

Is there another way?

6 Answers

In Python 3 you can use dict comprehension which can be an even shorter solution:

{key_expression(item) : value_expression(item) for item in something if condition}
  1. In case you want to filter a dictionary as in the original question:

    mydict = {'test1': {'y':  60},'test2': {'y':  70},'test3': {'y':  80}}
    s = {k : r for k,r in mydict.items() if r['y'] < 75 }
    > {'test1': {'y': 60}, 'test2': {'y': 70}}
    
  2. Or we can even create something out of a list or range. E.g. if we want a dictionary with all odd square numbers:

    {i : i**2 for i in range(11) if i % 2 == 1}
    > {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
    
Related