The script below works but I was wondering if there is a faster solution? With very large dictionary lists I noticed a small delay.
JavaScript
x
18
18
1
from collections import defaultdict
2
3
input = [{"first": 1.56,
4
"second": [1, 2, 3, 4]}, {"first": 7.786,
5
"second": [5, 6, 7, 8]}, {"first": 4.4,
6
"second": [9, 10, 11, 12]}]
7
output = [{"first": [1.56, 7.786, 4.4],
8
"second":[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]}]
9
10
my_dictionary = defaultdict(list)
11
for item in input:
12
for key, value in item.items():
13
my_dictionary[key].append(value)
14
print(my_dictionary)
15
16
#defaultdict(<class 'list'>, {'first': [1.56, 7.786, 4.4], 'second': [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]})
17
18
Advertisement
Answer
It seems keys in the dictionaries are the same, so you could use a dict comprehension:
JavaScript
1
2
1
out = {k:[d[k] for d in input] for k in input[0]}
2
Another pretty fast alternative is to use the cytoolz
module.
JavaScript
1
4
1
# pip install cytoolz
2
from cytoolz.dicttoolz import merge_with
3
out = merge_with(list, *input)
4
Output:
JavaScript
1
3
1
{'first': [1.56, 7.786, 4.4],
2
'second': [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]}
3
Timings:
JavaScript
1
14
14
1
>>> my_input = input * 10000
2
>>> %%timeit
3
my_dictionary = defaultdict(list)
4
for item in my_input:
5
for key, value in item.items():
6
my_dictionary[key].append(value)
7
20.3 ms ± 2.49 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
8
9
>>> %timeit out = {k:[d[k] for d in my_input] for k in my_input[0]}
10
4.65 ms ± 541 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
11
12
>>> %timeit out = merge_with(list, *my_input)
13
5.58 ms ± 2.09 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)
14