Set or update dictionary entries code pattern in Python -


given dict following format:

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

i updating dict_list in 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 way make code shorter using native constructs (i.e. no additional methods)? increasingly encountering data "set or update" pattern in code, , wondering whether there more concise way 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 floats represent john solver's daily expenses in dollars.

if possible, we'd keep using 2 long lists instead of many date-expense pairs, we'd conveniently perform sum of expenses operation using sum(dict_list['john solver'][1]).

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), set d[k]=d if k not in d 

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -