I have a nested dictionary and I want to concatenate the items of the nested dictionaries:
import random
nested_dict = {
k: {
'val0': random.sample(range(100), 2),
'val1': random.sample(range(100), 2),
}
for k in 'abcd'
}
I can make it with a double-loop like this:
from collections import defaultdict
dp_dict= defaultdict(list)
for v in nested_dict.values():
for k, v_nested in v.items():
dp_dict[k].append(v_nested)
val0 = dp_dict['val0']
val1 = dp_dict['val1']
is there a more Pythonic/elegant way to do it?
NB
one solution is to use Pandas, however, this solution is quite ineficcient (X300 slower)
import pandas as pd
val0, val1 = pd.DataFrame(nested_dict).loc[['val0', 'val1']].values
you could use a dictionary comprehension combined with list comprehension..
result = {
key: [v[key] for v in nested_dict.values()]
for key in next(iter(nested_dict.values()))
}
val0, val1 = result['val0'], result['val1']
Assumptions
Dict size: 10
Iterations: 1000
Defaultdict: 0.002345 sec
Comprehension: 0.001876 sec(2x fatser)
I would use List Comprehensions
example:
val0 = [v['val0'] for v in nested_dict.values()]
val1 = [v['val1'] for v in nested_dict.values()]
your full code to test:
from collections import defaultdict
import random
nested_dict = {
k: {
'val0': random.sample(range(100), 2),
'val1': random.sample(range(100), 2),
}
for k in 'abcd'
}
dp_dict= defaultdict(list)
for v in nested_dict.values():
for k, v_nested in v.items():
dp_dict[k].append(v_nested)
val0 = dp_dict['val0']
val1 = dp_dict['val1']
# List Comprehensions
val3 = [v['val0'] for v in nested_dict.values()]
val4 = [v['val1'] for v in nested_dict.values()]
List comprehensions offer conciseness, improved readability, faster performance, reduced boilerplate code, and allow inline conditional logic and nested operations.
CyberHorns is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1