It is better to store the values of "desc" as lists everywhere, even if they contain only one element. So you can do
for d in b:
print d['id']
for desc in d['desc']:
print desc
This will work for strings, just returning individual characters, which is not what you want.
And now a solution giving you a list of dicts lists:
a =[{'id': 1,'desc': 'smth'},{'id': 2,'desc': 'smthelse'},{'id': 1,'desc': 'smthelse2'},{'id': 1,'desc': 'smthelse3'}]
c = {}
for d in a:
c.setdefault(d['id'], []).append(d['desc'])
b = [{'id': k, 'desc': v} for k,v in c.iteritems()]
b Now:
[{'desc': ['smth', 'smthelse2', 'smthelse3'], 'id': 1},
{'desc': ['smthelse'], 'id': 2}]
source
share