Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set or update dictionary entries code pattern in Python

Given a dict with the following format:

dict_list = {key0: [list0,list1], key1: [list0,list1], ...}

I am currently updating dict_list in the following manner:

for key in list_of_possibly_new_keys:
   if key not in dict_list.keys():
      dict_list[key] = [list0, list1]
   else:
      dict_list[key][0].extend(list0)
      dict_list[key][1].extend(list1)

Is there a way to make this code shorter using native constructs (i.e. no additional methods)? I am increasingly encountering this data "set or update" pattern in my code, and wondering whether there is a more concise way to do this.

UPDATE/CLARIFICATION:

Sample actual contents of dict_list:

dict_list = {'John Solver': [['05/10/2013','05/14/2013','05/22/2013'],[20.33,40.12,10.13]]}

Where the floats could represent John Solver's daily expenses in US dollars.

If possible, we'd like to keep using two long lists instead of many date-expense pairs, as we'd like to conveniently perform a sum of expenses operation using sum(dict_list['John Solver'][1]).

like image 363
silvernightstar Avatar asked Aug 22 '26 11:08

silvernightstar


2 Answers

Unless this is homework, why can't you use a defaultdict here?

from collections import defaultdict
dict_list = defaultdict(list)

for key in list_of_possibly_new_keys:
    dict_list[key] += [list0, list1]

Updated for your example:

>>> from collections import defaultdict
>>> dict_list = defaultdict(lambda :[[], []])
>>> dict_list['John Solver'][0].append('05/10/2013')
>>> dict_list['John Solver'][1].append(20.33)
and so on

Aside: Turns out that due to the limited precision of floats, it's usually a terrible idea to use them to represent currency. Consider using the decimal module instead

like image 116
John La Rooy Avatar answered Aug 25 '26 00:08

John La Rooy


You can use dict.setdefault:

for key in list_of_possibly_new_keys:
      dict_list.setdefault(key,[]).extend([list0, list1])

help in dict.setdefault:

>>> dict.setdefault?
Type:       method_descriptor
String Form:<method 'setdefault' of 'dict' objects>
Namespace:  Python builtin
Docstring:  D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
like image 26
Ashwini Chaudhary Avatar answered Aug 25 '26 01:08

Ashwini Chaudhary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!