Given:
d = {'c': 3, 'b': 2, 'a': 1, 'd': 4, 'e': 5}
sorted_dict = d.keys()
sorted_dict = sorted(sorted_dict)
for key in sorted_dict:
print(key)
How do I make it so that it outputs every other key. Right now it outputs:
a
b
c
d
e
but I want it to output:
a
c
e
>Solution :
Python provides "slicing" for very powerful and elegant solutions to problems like this. It’s too big a topic to fully explain here but lot’s of information all over the net on this core topic, here’s a suggestion:
https://www.pythontutorial.net/advanced-python/python-slicing/
To solve your specific problem:
d = {'c': 3, 'b': 2, 'a': 1, 'd': 4, 'e': 5}
sorted_dict = d.keys()
sorted_dict = sorted(sorted_dict)
for key in sorted_dict[::2]:
print(key)
The [::2] here specifies that you want to take all of the sorted list from start to finish but in steps of 2 (ie. every other element)
Incidentally, you can dispense with the for loop and just print your list slice!..
d = {'c': 3, 'b': 2, 'a': 1, 'd': 4, 'e': 5}
sorted_dict = d.keys()
sorted_dict = sorted(sorted_dict)
print(sorted_dict[::2])
['a', 'c', 'e']