422,944 Members | 2,030 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 422,944 IT Pros & Developers. It's quick & easy.

check if an item exists in a dictionary. if yes, delete it, otherwise add it

P: 1
hi, im having a little problem here.
i want to check if an item exists in a dictionary, if yes, i have to delete it. otherwise i have to add it.

Expand|Select|Wrap|Line Numbers
  1. d = {'1':2}
  2.  
  3. if '1' not in d.items():
  4.     d = {'1':2}
  5. else:
  6.     del (d['1'])
  7.  
  8. print (d)
  9.  
but it seems wrong. i only just started so help would be greatly appreciated. thanks!
Oct 18 '16 #1
Share this Question
Share on Google+
2 Replies


Expert 100+
P: 594
Adding, changing and deleting items from a dictionary is in most basic tutorials. Tutorials are write once, read many, so people don't have to answer the same basic questions over and over https://wiki.python.org/moin/BeginnersGuide/Programmers
Oct 18 '16 #2

P: 3
I quite tryed to figure it out, im still a begginer but i've done this! Hope it helps :)

Expand|Select|Wrap|Line Numbers
  1. d = {'1':2}
  2. d2 = {'1':2}
  3. if d != d2:
  4.     d['1']= 2
  5. else:
  6.     del (d['1'])
  7. print d
Oct 22 '16 #3

Post your reply

Sign in to post your reply or Sign up for a free account.