append to a ldictionary value list 1

append to a ldictionary value list

#list.append returns None, since it is an in-place operation and you are 
#assigning it back to dic[key]. So, the next time when you do 
#dic.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)
from collections import defaultdict
dates_dict = defaultdict(list)
for key, date in cur:

Here is what the above code is Doing:
1. Create a defaultdict with a default value of list.
2. Iterate over the list of tuples.
3. For each tuple, append the date to the list in the dict.
4. If the key doesn’t exist, the defaultdict will create it and set the default value (list) for it.

Similar Posts