How to create a list of two dictionaries?

I am trying to write a model in a GAE data warehouse that will have three fields: date, integer, integer.

class fusSent(db.Model): """ Models a list of the follow-ups due and follow-ups sent """ date_created = db.DateTimeProperty(auto_now_add=True) fu_date = db.DateProperty() fus_due = db.IntegerProperty() fus_sent = db.IntegerProperty() 

This data comes from two different dictionaries with corresponding keys (dates). See below.

 fus_d = {2013-01-01: 1, 2013-04-01: 1, 2013-02-01: 1, 2013-03-01: 1} fus_s = {2013-01-01: 0, 2013-04-01: 0, 2013-02-01: 1, 2013-03-01: 1} 

I assume that I need to combine the dictionaries into a list (for example, the one below) in order to store it in a data warehouse. However, I am not entirely sure that this is the best approach.

 fu_list = [(2013-01-01, 1, 0), (2013-04-01, 1, 0), (2013-02-01, 1, 1), (2013-03-01, 1, 1)] 
+4
source share
3 answers

I hope the fus_d and fus_s do have dates, because your example 2013-01-01 is actually a mathematical expression that evaluates to 2011 . But the following should work

 s = set(fus_d.keys()) s.update(fus_s.keys()) fu_list = [(k, fus_d.get(k), fus_s.get(k)) for k in s] 

Edit: also with python 2.7 you can use viewkeys directly from dict instead of using set .

 fu_list = [(k, fus_d.get(k), fus_s.get(k)) for k in fus_d.viewkeys() | fus_s] 
+6
source

Improving @cmd's answer.

To write to the database, you must create a list of model instances and call db.put to save them to the database, for example:

 fus_d = {'2013-01-01': 1, '2013-04-01': 1, '2013-02-01': 1, '2013-03-01': 1} fus_s = {'2013-01-01': 0, '2013-04-01': 0, '2013-02-01': 1, '2013-03-01': 1} s = set(fus_d.keys()) s.update(fus_s.keys()) fu_list = [fusSent(fu_date=k, fus_due=fus_d.get(k, 0), fus_sent=fus_s.get(k, 0)) for k in s] db.put(fu_list) 
+2
source

@cmd has code to generate the requested list, but this will not end up in the data store. This code will create the entities and save them:

 s = set(fus_d.keys()) s.update(fus_s.keys()) for k in s: sent = fusSent(fu_date=k, fus_due=fus_d.get(k), fus_sent=fus_s.get(k)) sent.put() 
+1
source

Source: https://habr.com/ru/post/1485518/


All Articles