Let's say I have a dictionary with the keys being all the numbers 1-10. And I want to iterate through that excluding keys 6-8. Is it possible to do something like
for key in dictionary.keys().exclude([1,2,3])
I've made up .exclude()
to demonstrate what I want to do.
Remember that the keys of a dictionary are unique, so using set
operations would be suitable (and are very performant):
dictionary = {i: i for i in range(1, 11, 1)}
for key in set(dictionary) - set([1, 2, 3]):
print(key)
You can also use a set literal instead of an explicit set
conversion like this:
for key in set(dictionary) - {1, 2, 3}:
print(key)
And, as pointed out in the comments, dictionary.keys()
as you originally had it would behave in the same way as set(dictionary)
.
A technique to bypass a few iterations from a loop would be to use continue
.
dictionary = {1: 1, 2: 2, 3 : 3, 4: 4}
for key in dictionary:
if key in {1, 2, 3}:
continue
print(key)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With