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
CodePudding user response:
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']
CodePudding user response:
sorted_dict = d.keys()
sorted_dict = sorted(sorted_dict)
for key in range(len(sorted_dict),2): print(key)
CodePudding user response:
Let d
be the dictionary to print alternating rows on.
d = {'c': 3, 'b': 2, 'a': 1, 'd': 4, 'e': 5}
d = dict(sorted(d.items()))
Dictionaries are sequences, just like lists. Similar techniques can be used for both to keep alternating entries:
for i, key in enumerate(d.keys()):
if i % 2 == 0:
print(key)
Or:
for key in list(d.keys())[::2]:
print(key)