Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to iterate through all of a dictionary's keys except a specific subset?

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.

like image 579
Anonymous12332313 Avatar asked Oct 19 '25 11:10

Anonymous12332313


2 Answers

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).

like image 65
costaparas Avatar answered Oct 22 '25 02:10

costaparas


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)
like image 33
Abhilash Avatar answered Oct 22 '25 00:10

Abhilash