Jan-25-2018, 04:48 PM
That is a dictionary comprehension. Comprehensions are pretty natural once you are into python but can be a bit arcane when you first start.
So, lets start with the iteration.
If we have a dict:
So, lets start with the iteration.
If we have a dict:
>>> a = {"a" : 1, "b" : 2, "c" : 3}We can get tuples of the key:value pairs with
items()
>>> list(a.items()) [('a', 1), ('c', 3), ('b', 2)]So we can iterate through these tuples:
>>> for k,v in a.items(): ... print(k,v) ... ('a', 1) ('c', 3) ('b', 2) >>>So making the dict without the comprehension:
>>> b = {} # make an empty dict >>> for k,v in a.items(): ... if v % 2: # is the value odd ... b[k] = v # set key to value ... >>> b {'a': 1, 'c': 3}And with the comprehension it is much more concise:
>>> c = {k:v for k,v in a.items() if v % 2} >>> c {'a': 1, 'c': 3}