0

I want to convert the Current data format into Expected result

The items should be ordered as origin.

How could I do it in elegant way with Python

Current data format

[{'_id': 1800, 'count': 32},
 .....
 {'_id': 1892, 'count': 1},
 {'_id': 1899, 'count': 13}]

Expected result

 {"_id":[1800,1892,1899], "count":[32,1,13]}
Calum
  • 1,889
  • 2
  • 18
  • 36
user3675188
  • 7,271
  • 11
  • 40
  • 76

4 Answers4

1

Try this using defaultdict

from collections import defaultdict
l = [{'_id': 1800, 'count': 32},
 {'_id': 1892, 'count': 1},
 {'_id': 1899, 'count': 13}]

d = defaultdict(list)
for i in l:
    for j,k in i.items():
        d[j].append(k)

>>>d
defaultdict(<type 'list'>, {'count': [32, 1, 13], '_id': [1800, 1892, 1899]})

OR

using Counter

from collections import Counter

l = [{i:[j] for i,j in d.items()} for d in l]
result_counter = Counter()
for i in l:
    result_counter.update(i)

>>>result_counter
Counter({'_id': [1800, 1892, 1899], 'count': [32, 1, 13]})
itzMEonTV
  • 19,851
  • 4
  • 39
  • 49
1

From python collections docs:

>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
...     d[k].append(v)
...
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
pacholik
  • 8,607
  • 9
  • 43
  • 55
1

You can simply traverse the list and construct the required dictionary.

In [2]: l = [{'_id': 1800, 'count': 32}, {'_id': 1892, 'count': 1}, {'_id': 1899, 'count': 13}]

In [3]: {'_id': [data['_id'] for data in l], 'count': [data['count'] for data in l]}
Out[3]: {'_id': [1800, 1892, 1899], 'count': [32, 1, 13]}
taskinoor
  • 45,586
  • 12
  • 116
  • 142
0
>>> data
[{'count': 32, '_id': 1800}, {'count': 1, '_id': 1892}, {'count': 13, '_id': 1899}]
>>> result = {key:[] for key in data[0]}
>>> for d in data:
...     for k in d:
...         result[k].append(d[k])
... 
>>> result
{'count': [32, 1, 13], '_id': [1800, 1892, 1899]}
timgeb
  • 76,762
  • 20
  • 123
  • 145