-1

I HAVE to use pop() method in Python3 to delete all states that starts with 'M'. Can't figure out how to keep the size of the dictionary.

states = {
        'AK': 'Alaska',
        'AL': 'Alabama',
        'AR': 'Arkansas',
        'MN': 'Minnesota',
        'MO': 'Missouri',
        'MP': 'Northern Mariana Islands',
        'MS': 'Mississippi',
}

for key, val in states.items():
    if key[0] == 'M':
        states.pop(key, val)
RuntimeError                              Traceback (most recent call last)
Input In [45], in <cell line: 62>()
     60 # your code here
     61 newdic = {}
---> 62 for key, val in states.items():
     63     if key[0] == 'M':
     64         states.pop(key,val)

RuntimeError: dictionary changed size during iteration
wjandrea
  • 28,235
  • 9
  • 60
  • 81

2 Answers2

2

If, as you say, you must use pop, then create a separate set of the key values and iterate over that. Altering the size of something you are iterating over is a big no-no.

states = {
        'AK': 'Alaska',
        'AL': 'Alabama',
        'AR': 'Arkansas',
        'MN': 'Minnesota',
        'MO': 'Missouri',
        'MP': 'Northern Mariana Islands',
        'MS': 'Mississippi',
}

for key in set(states.keys()):
    if key[0] == 'M':
        states.pop(key)

print(states)

Output:

{'AK': 'Alaska', 'AL': 'Alabama', 'AR': 'Arkansas'}
AirSquid
  • 10,214
  • 2
  • 7
  • 31
  • 2
    This is much better than creating a whole new dict as the other answer suggests. However I'd go with a tuple instead of a set, as its creation should be a tad faster – DeepSpace Jul 09 '22 at 00:07
1

Make a copy of the dictionary, iterate over it, and pop from the original dictionary.

The code:

 states = {
        'AK': 'Alaska',
        'AL': 'Alabama',
        'AR': 'Arkansas',
        'MN': 'Minnesota',
        'MO': 'Missouri',
        'MP': 'Northern Mariana Islands',
        'MS': 'Mississippi',
}

for key, val in states.copy().items():
    if key[0] == 'M':
        states.pop(key)

Output:

{'AK': 'Alaska', 'AL': 'Alabama', 'AR': 'Arkansas'}
Ryan
  • 1,081
  • 6
  • 14
  • Thank yoy Ryan. I have to check out how to work with sets. I'm unable to upvote right now but I did it for both questions: "Thanks for the feedback! You need at least 15 reputation to cast a vote, but your feedback has been recorded." – Alejandro CM Jul 09 '22 at 00:04