Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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:
- thedict = [] # You can use existing dict as well
- # function takes a dict, a list name and the element
- def add_to_list_in_dict(thedict, listname, element):
- if listname in thedict:
- l = thedict[listname]
- print("%s already has %d elements." % (listname, len(l)))
- else:
- thedict[listname] = []
- print("Created %s." % listname)
- thedict[listname].append(element)
- print("Added %s to %s." % (element, listname))
- thedict[listname].append(element)
- print("Added %s to %s." % (element, listname))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement