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?
The idea of comprehension is not just unique to lists in Python. Dictionaries, one of the commonly used data structures in data science, can also do comprehension.
Using dict() method we can convert list comprehension to the dictionary. Here we will pass the list_comprehension like a list of tuple values such that the first value act as a key in the dictionary and the second value act as the value in the dictionary.
List comprehensions are constructed from brackets containing an expression, which is followed by a for clause, that is [item-expression for item in iterator] or [x for x in iterator], and can then be followed by further for or if clauses: [item-expression for item in iterator if conditional].
Its syntax is the same as List Comprehension. It returns a generator object. A dict comprehension, in contrast, to list and set comprehensions, needs two expressions separated with a colon. The expression can also be tuple in List comprehension and Set comprehension.
You can do this:
s = dict([ (k,r) for k,r in mydict.iteritems() if r['x'] > 92 and r['x'] < 95 and r['y'] > 70 and r['y'] < 75 ])
This takes a dict as you specified and returns a 'filtered' dict.
If dct
is
{'test1420': {'y': '060', 'x': '070', 'fname': 'test1420'}, 'test277': {'y': 72, 'x': 94, 'fname': 'test277'},}
Perhaps you are looking for something like:
[ subdct for key,subdct in dct.iteritems() if 92<subdct['x']<95 and 70<subdct['y']<75 ]
A little nicety is that Python allows you to chain inequalities:
92<dct[key]['x']<95
instead of
if r['x'] > 92 and r['x'] < 95
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:
{ n: n*n for n in range(5) } # dict comprehension {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
In Python2 the equivalent would be
dict( (n,n*n) for n in range(5) )
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With