Videos
I am trying to add a list, or a tuple of lists, as the value to a key inside a dictionary. I'm starting with a dictionary that has empty lists as values, and then adding to the value of each key inside a loop like this:
dict = {'key1': [], 'key2': [], 'key3': []}
list = ['a', 'b']
for key,value in dict.items():
# dict[key].append(list)
value.append(list)
print(dict)What is the difference between dict[key].append(list) and value.append(list)? They both produce the same dictionary when the other is commented out.
Further, how would I add a second list to one of these values as a tuple? Something like adding the list ['c', 'd'] to key2, like this:
{'key1': [['a', 'b']], 'key2': [['a', 'b'], ['c', 'd']], 'key3': [['a', 'b']]}Thanks for any replies!
list.append returns None, since it is an in-place operation and you are assigning it back to dates_dict[key]. So, the next time when you do dates_dict.get(key, []).append you are actually doing None.append. That is why it is failing. Instead, you can simply do
dates_dict.setdefault(key, []).append(date)
But, we have collections.defaultdict for this purpose only. You can do something like this
from collections import defaultdict
dates_dict = defaultdict(list)
for key, date in cur:
dates_dict[key].append(date)
This will create a new list object, if the key is not found in the dictionary.
Note: Since the defaultdict will create a new list if the key is not found in the dictionary, this will have unintented side-effects. For example, if you simply want to retrieve a value for the key, which is not there, it will create a new list and return it.
Is there a more elegant way to write this code?
Use collections.defaultdict:
from collections import defaultdict
dates_dict = defaultdict(list)
for key, date in cur:
dates_dict[key].append(date)