I want to update the dictionary. But its generating , RuntimeError: dictionary changed size during iteration

Viewed 58
dic1={"God Arises":"Ali","Mysterious":"sherry"}
name= input("Enter Your Name: ")

bookNam =input("Enter book name that you want to lend: ")
for key1 in dic1:
        if key1==bookNam:
            print("Book Not available")
        else:
            dic1.update({bookNam:name})
2 Answers

Don't use for-loop to check if key is in the dictionary. Use in operator. For example:

dic1 = {"God Arises": "Ali", "Mysterious": "sherry"}
name = input("Enter Your Name: ")

bookNam = input("Enter book name that you want to lend: ")
if bookNam in dic1:
    print("Book Not available")
else:
    dic1.update({bookNam: name})

No need to loop through your dictionary.

You can either use bookNam in dict1.keys()

You can also use dic1.get(bookNam) is not None

Or a perfectly pythonic way by trying to access the key and catch the exception

try:
    print(f"Book '{dic1[bookNam]}' Not available")
except KeyError:
    dic1.update({bookNam: name})

If you really need to loop through a dictionary and add/remove items, I would suggest to make a copy of the keys and loop through those ones instead.

In your case it would work if you used this:

for key1 in list(dic1.keys()):
    if key1 == bookNam:
        print("Book Not available")
        break
 else:
     dic1.update({bookNam:name})
Related