Advertisement
Guest User

Untitled

a guest
Feb 19th, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.85 KB | None | 0 0
  1. This function adds an element to a list inside a dict of lists. Rewrite it to use a try-except statement which handles a possible KeyError if the list with the name provided doesn’t exist in the dictionary yet, instead of checking beforehand whether it does. Include else and finally clauses in your try-except block:
  2.  
  3. thedict = [] # You can use existing dict as well
  4. # function takes a dict, a list name and the element
  5. def add_to_list_in_dict(thedict, listname, element):
  6.     if listname in thedict:
  7.         l = thedict[listname]
  8.         print("%s already has %d elements." % (listname, len(l)))
  9.     else:
  10.         thedict[listname] = []
  11.         print("Created %s." % listname)
  12.         thedict[listname].append(element)
  13.         print("Added %s to %s." % (element, listname))
  14. thedict[listname].append(element)
  15. print("Added %s to %s." % (element, listname))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement