-1

I have a quite big list of dictionaries of length 2, namely

a=[{'id': 977950, 'account_id': u'BKDFIU'}, {'id':45637, 'account_id': u'FGDG'}, {'id': 764325, 'account_id': u'HGDER$Y'}, {'id': 1011243, 'account_id': u’REW$LP'}, {'id': 1022741, 'account_id': u'YUFDNGFN'}, {'id': 45637, 'account_id': None}, {'id': 764325, 'account_id': u'HGDERYTH'}]

Now, I want whereever there is a match of dictionary key those values should be concatenated

{977950: [u'BKDFIU'], 45637: [u'FGDG', None], 764325:[u'HGDER$Y', u'HGDERYTH'], 1011243:[u’REW$LP'], 1022741: [u'YUFDNGFN']}

I am trying in conventional methods, but is there any better way in comprehension that i might use? I have searched everywhere, but unable to find similar.

Please let me know if you can think of a way?

SudipM
  • 416
  • 7
  • 14

1 Answers1

1

Comprehensions won't help here. You can do it with a comprehension but it would be inefficient. You can use collections.defaultdict, or dict.setdefault, or an if ... in ... guard, but the principle is the same: iterate over items, and add elements one by one.

d = {}
for item in a:
    d.setdefault(item["id"], []).append(item["account_id"])
Amadan
  • 191,408
  • 23
  • 240
  • 301