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
#2
Quote:I am trying to find every other value in a dictionary.
Do you mean a list? As this doesn't make much sense for a dictionary.

If you mean a list, the easiest way is slicing:
>>> my_list
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> my_list[::2]
['a', 'c', 'e', 'g']
>>> for letter in my_list[::2]:
...     print(letter)
...
a
c
e
g
>>>
Edit:
Okay realized that was a typo and you mean even/odd.
You have basically the right idea:
>>> my_list
[6, 9, 8, 3, 5, 1, 10, 10, 4, 6]
>>> for num in my_list:
...     if num % 2:
...         print(num)
...
9
3
5
1
>>> [num for num in my_list if num % 2]
[9, 3, 5, 1]
>>>
Reply


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

Possibly Related Threads…
Thread Author Replies Views Last Post
  Looping to Create Nested Dictionary gngu2691 10 33,968 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