Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I print out every other key in a dictionary?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading