Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

combine values of several objects into a single dictionary

I am fetching these rows from db:

blog_id='12', field_name='title', translation='title12 in en', lang='en'
blog_id='12', field_name='desc', translation='desc12 in en', lang='en'

blog_id='13', field_name='title', translation='title13 in en', lang='en'
blog_id='13', field_name='desc', translation='desc13 in en', lang='en'
....

and I want to build a single dictionary for each blog_id: e.g.

[
   {'blog': '12', 'title': 'title12 in en', 'desc': 'desc12 in en'},
   {'blog': '13', 'title': 'title13 in en', 'desc': 'desc13 in en'},
   ....
]

I am trying this way:

res = []
dict_ = {}
for trans in translations: # 'translations' is QuerySet, already filtered by 'en'  
    if trans.blog_id in dict_.values():
        dict_[trans.field_name] = trans.translation
    else:
        dict_['blog'] = trans.blog_id
        dict_[trans.field_name] = trans.translation

    res.append(dict_)

but this is soo wrong, res contains here blog 13 3 times and blog 12 isnot even in the final list. I feel so dumb right now, what am I missing?

like image 379
doniyor Avatar asked Dec 30 '15 16:12

doniyor


People also ask

How do you create a dictionary using multiple values?

In python, if we want a dictionary in which one key has multiple values, then we need to associate an object with each key as value. This value object should be capable of having various values inside it. We can either use a tuple or a list as a value in the dictionary to associate multiple values with a key.

How do you add multiple key-value pairs to a dictionary?

In Python, we can add multiple key-value pairs to an existing dictionary. This is achieved by using the update() method. This method takes an argument of type dict or any iterable that has the length of two - like ((key1, value1),) , and updates the dictionary with new key-value pairs.


1 Answers

First, accumulate all the data corresponding to every blog_id in a dictionary, like this

groups = {}
for trans in translations:
  groups.setdefault(trans.blog_id, {})[trans.field_name] = trans.translation

Now, attach the corresponding blog_id to all the accumulated dictionaries,

for key in groups:
  groups[key]['blog'] = key

Now, just get all the values of the groups, with groups.values() to get the result.

Note: If you want to retain the original order of elements based on the blog_id, then instead of using a normal dictionary, use collections.OrderedDict, like this

from collections import OrderedDict
groups = OrderedDict()
...
like image 193
thefourtheye Avatar answered Nov 14 '22 22:11

thefourtheye