Kex
Kex

Reputation: 776

How to create a nested dictionary from a datastore model?

I am working on this problem a couple of days, my idea is from this model:


class oceni(db.Model):
    user = db.UserProperty()
    weight = db.FloatProperty()
    item = db.StringProperty()

..to create a dictionary in this format:


collection = dict()
collection = {
    'user1':{'item1':weight1,'item2':weight2..},
    'user2':{'item3':weight3,'item4':weight4..},
..}

..and as far as I reached is this:


kontenier = db.GqlQuery('SELECT * FROM oceni')

        kolekcija = dict()
        tmp = dict()
        lista = []
        for it in kontenier:
            lista.append(it.user)
        set = []
        for e in lista:
            if e not in set:
                set.append(e)
        for i in set:
            kontenier = db.GqlQuery('SELECT * FROM oceni WHERE user=:1',i)
            for it in kontenier:
                tmp[it.item]=it.weight
            kolekcija[i]=tmp



..but this creates a dictionary where all the users have the same dictionary with items and their weight. I know this isn't the most pythonic way, but I'm new to this so I will be eager to learn something more about this problem.

Upvotes: 1

Views: 731

Answers (1)

btilly
btilly

Reputation: 46408

I've used your variable names your notation in this snippet.

kontenier = db.GqlQuery('SELECT * FROM oceni')
kolekcija = {}
for it in kontenier:
    if it.user not in kolekcija:
        kolekcija[it.user] = {}
    kolekcija[it.user][it.item] = it.weight

Upvotes: 3

Related Questions