Home > database >  Group values by keys in list of dictionaries
Group values by keys in list of dictionaries

Time:11-24

What I have:

d = {datetime.date(2013, 1, 1): {'15169': 2, '56203': 5, '2519': 3, '18144': 3, '9737': 4},
datetime.date(2014, 1, 1): {'15169': 5, '56203': 3, '2519': 2, '18144': 1, '9737': 0}}

What I want:

{15169:[2,5], 56203:[5,3], 2519:[3,2], 18144:[3,1], 9737:[4,0]}

Is there any straight-forward method to achieve this? Tried multiple ways but looks like there's not any straight-forward method.

CodePudding user response:

ans = {}
[[ans.setdefault(k, []).append(v) for k, v in x.items()] for x in d.values()]
ans
# {'15169': [2, 5],
#  '56203': [5, 3],
#  '2519': [3, 2],
#  '18144': [3, 1],
#  '9737': [4, 0]}

Or using pandas

pd.DataFrame(d).apply(list, axis=1).to_dict()
# {'15169': [2, 5],
#  '56203': [5, 3],
#  '2519': [3, 2],
#  '18144': [3, 1],
#  '9737': [4, 0]}

CodePudding user response:

as straightforward as I can imagine, use defaultdict:

from collections import defaultdict

out = defaultdict(list)

for x in d.values():
    for k,v in x.items():
        out[k].append(v)

Output:

defaultdict(list,
            {'15169': [2, 5],
             '56203': [5, 3],
             '2519': [3, 2],
             '18144': [3, 1],
             '9737': [4, 0]})

CodePudding user response:

I may be wrong but I don't know of any method that does what you want to achieve. Even then, achieving that particular result should not be difficult at all. I think the best way would be to implement your own group-by() method! Try to reason about the steps that would take to group the data you have in your original Dictionary into the object you need. It looks like you are grouping by p->d with p being a Dictionary key and d being a key to that property in return. That is exactly a grouping by p->d! I don't know if this answer is clear enough, I don't want to provide code so that you don't miss your learning experience, but should you need it just ask and I'll try to provide an example for you :)

  • Related