Python Forum
Looping through a dictionary for every other value
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Looping through a dictionary for every other value
#8
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:
>>> 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}
Reply


Messages In This Thread
RE: Looping through a dictionary for every other value - by Mekire - Jan-25-2018, 04:48 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Looping to Create Nested Dictionary gngu2691 10 33,804 Jun-22-2018, 04:11 PM
Last Post: anickone

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020