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?
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.
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.
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()
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With