iamnewuser
iamnewuser

Reputation: 360

Add the dictionary instead of overwrite - defaultdict

I have a dictionary named "n" which will have a key value relation in it(Dict inside dict).

Here Key will be an tenant_id (b77865b66fd544e0841aa7dbca8bdc97, 7b73b9644e8242b3a740afc4659d9829).

So Dict will be having a key value pair relation in such a way that it tenant_id and its related instance names in it.

Sample code:

    n = defaultdict(dict)

    r = q.all()

    # For getting the values of sql obj
    for m in r:

            g = m.__dict__

            g.pop('_sa_instance_state', None)

            tenant_id = g['tenant_id']

            n[tenant_id] = g

    n = json.dumps(n, default=json_util.default)

So now one tenant will be having more that one instances.

Here I am facing the issue with overwriting of values related to the key.

I need to add the dict here instead of overwriting it.

Here I have provided the same results to make sense.

Expected result:

{u'b77865b66fd544e0841aa7dbca8bdc97': {u'instance_name': u'instance_for_test'},{u'instance_name': u'new_instance'}, u'7b73b9644e8242b3a740afc4659d9829': {u'instance_name': u'demo'}}

Actual result:

{u'b77865b66fd544e0841aa7dbca8bdc97': {u'instance_name': u'new_instance'}, u'7b73b9644e8242b3a740afc4659d9829': {u'instance_name': u'demo'}}

Someone let me know the solution for the issue.

Note:

I have tried append and extend etc., But as it is Dict it seems not to be working.

Upvotes: 2

Views: 1711

Answers (1)

phihag
phihag

Reputation: 287755

n = defaultdict(dict)
# ...
n[tenant_id] = g

indeed overwrites the key with the value of tenant_id. Instead of setting a value with =, call a method on the result, like this:

n = defaultdict(dict)
n[tenant_id].update(g)

Seeing that your expected result is not valid Python, you may want to have list values instead of dicts. Easy:

n = defaultdict(list)
# ...
n[tenant_id].append(g)

Upvotes: 2

Related Questions