Day 2: Clever Stuff Python Challenge
Read this slide as text
Clever Stuff Python Challenge. What would the output of this code be? Extra points if you can identify the bug in this code. The code defines list_to_dict(items, output={}), documented as 'Convert a list of key value pairs to dictionary': for each item it sets output[item[0]] = item[1], then returns output. It sets products to [['stuffing', 3.75], ['wrapping paper', 0.65], ['mince pies', 2.99]] and calls products_dict = list_to_dict(products). It sets users to [['rudolf', 20], ['dasher', 8], ['prancer', 19]] and calls users_dict = list_to_dict(users). Finally it prints products_dict and then users_dict.
Reveal the answer
Both lines print the same dictionary: {'stuffing': 3.75, 'wrapping paper': 0.65, 'mince pies': 2.99, 'rudolf': 20, 'dasher': 8, 'prancer': 19} The bug: the default value output={} is created once, when the function is defined, so every call that doesn't pass its own output shares and adds to the same dictionary. Use output=None and create a new dictionary inside the function instead.
![Clever Stuff Python Challenge. What would the output of this code be? Extra points if you can identify the bug in this code. The code defines list_to_dict(items, output={}), documented as 'Convert a list of key value pairs to dictionary': for each item it sets output[item[0]] = item[1], then returns output. It sets products to [['stuffing', 3.75], ['wrapping paper', 0.65], ['mince pies', 2.99]] and calls products_dict = list_to_dict(products). It sets users to [['rudolf', 20], ['dasher', 8], ['prancer', 19]] and calls users_dict = list_to_dict(users). Finally it prints products_dict and then users_dict.](/_astro/slide-1.C1cxYaqG_1HwWes.png)