2
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})
Barbaros Özhan
  • 59,113
  • 10
  • 31
  • 55
BABA ADAM
  • 21
  • 3
  • You are right it works but if i want to use for loop then what can i do, i have used it in this way but its also executing the else part every time whether condition is true or false....................................................................... 'name2= input("Enter Your Name: ") bookNam = input("Enter book name that you want to lend: ") for key1 in list(dic1.keys()): if key1 == bookNam: print(f"Book Not available") else: dic1.update({bookNam:name2})' – BABA ADAM May 09 '21 at 21:28
  • Welcome to SO, please comment in the answer section not in the question itself. I have updated the answer to address what you are observing with the for loop – Nic Laforge May 09 '21 at 21:45
  • Does this answer your question? [How to avoid "RuntimeError: dictionary changed size during iteration" error?](https://stackoverflow.com/questions/11941817/how-to-avoid-runtimeerror-dictionary-changed-size-during-iteration-error) – Adrian W May 09 '21 at 21:50

2 Answers2

4

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})
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
1

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})
Nic Laforge
  • 1,776
  • 1
  • 8
  • 14