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?
You can do this:
This takes a dict as you specified and returns a 'filtered' dict.
If
dct
isPerhaps you are looking for something like:
A little nicety is that Python allows you to chain inequalities:
instead of
Note also that above I've written a list comprehension, so you get back a list (in this case, of dicts).
In Python3 there are such things as dict comprehensions as well:
In Python2 the equivalent would be
I'm not sure if you are looking for a list of dicts or a dict of dicts, but if you understand the examples above, it is easy to modify my answer to get what you want.
Is there another way?
Why not consider the use of some lightweight objects?
You can still use list comprehensions for gathering or filtering the objects, and gain a lot in clarity / extensibility.
Sounds like you want something like:
Some notes on this code:
low < value < high
You can get a list of the values of a dictionary d with
d.values()
. Your list comprehension should work using that, although I'm a little unclear what exactly you want the output to be.