Home > OS >  Using a for loop and if statement in Python
Using a for loop and if statement in Python

Time:01-14

I am trying to solve a problem similar to this one below:

You are provided with a dictionary, for loop through all the values in the dictionary and check if they are equal to 45. If they are, delete them from the list. Below is the dictionary:

this_dict = {
    "dogs val":45, "sheep val":475, "cats val":33, "fish val":425, "crab val":11, "monkey val":45, "shark val":45,
    "badger val":45,"octopus val":55,"cheetah val":45,"owl val":656

I am then hoping to print and output the dictionary provided, but with all the key:value pairs with a value of 45 removed.

This is what I have tried thus far:

for i in this_dict:
  if this_dict[i] == 45:
    del this_dict[i]

CodePudding user response:

Why not filter in a dict comprehension ?

Rather than deleting in original dict, you create a new one and can reassign to your original dict variable.

{k: v for k, v in this_dict.items() if v != 45}

gives

{'sheep val': 475,
 'cats val': 33,
 'fish val': 425,
 'crab val': 11,
 'octopus val': 55,
 'owl val': 656}

Full demo

this_dict = {
    "dogs val": 45,
    "sheep val": 475,
    "cats val": 33,
    "fish val": 425,
    "crab val": 11,
    "monkey val": 45,
    "shark val": 45,
    "badger val": 45,
    "octopus val": 55,
    "cheetah val": 45,
    "owl val":656
}

id(this_dict)  # 4478365376

this_dict = {k: v for k, v in this_dict.items() if v != 45}

id(this_dict)  # 4474822144  different id, it's a new dict

CodePudding user response:

I guess you got a RuntimeError because you iterate on the dictionary which changes. If you create a list with the keys of the dict, you do not have this problem:

this_dict = {"dogs val":45, "sheep val":475, "cats val":33, "fish val":425, "crab val":11, "monkey val":45, "shark val":45, "badger val":45,"octopus val":55,"cheetah val":45,"owl val":656}

for i in list(this_dict.keys()):
    if this_dict[i] == 45:
        del this_dict[i]

CodePudding user response:

Your code did not work because you cannot modify the same dictionary you are iterating on. You receive that error:

RuntimeError: dictionary changed size during iteration

You can solve it using list, that make a copy of the dictionary:

for key in list(this_dict):
  if this_dict[key] == 45:
    del this_dict[key]

It would be a much more pythonic solution to use a dict comprehension, but using for loops was a requirement in the question.

CodePudding user response:

You should try the following:

for key in this_dict.keys():
    if this_dict[key] == 45:
        del this_dict[key]

Let me know if you have any questions.

  • Related