Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a list from two dictionaries?

I'm trying to write to a model in the GAE datastore 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 is coming from two different dictionaries which have matching 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} 

My guess is that I need to combine the dictionaries into a list (like the one below) in order to save it to the datastore. However, I'm not completely sure 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)]
like image 274
655321 Avatar asked Jan 13 '23 04:01

655321


1 Answers

I hope fus_d and fus_s dictionaries actually have dates, because your example of 2013-01-01 is actually a math expression that evals 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 the viewkeys directly from the dict instead of using a set.

fu_list = [(k, fus_d.get(k), fus_s.get(k)) for k in fus_d.viewkeys() | fus_s]
like image 200
cmd Avatar answered Jan 21 '23 18:01

cmd