I have a dictionary in the following form:
JavaScript
x
11
11
1
dic = {
2
"Pbat_ch[1]": 1.976662114355723e-81,
3
"Pbat_ch[2]": -1.449552217194197e-81,
4
"Pbat_dis[1]": 2.8808538131862966,
5
"Pbat_dis[2]": 2.0268679389242448,
6
"Ebat[1]": 10.0,
7
"Ebat[2]": 6.799051318681892,
8
"Pgrid[1]": 115.48659741294217,
9
"Pgrid[2]": 115.4865974120957,
10
}
11
I need to get 4 lists of the following form:
JavaScript
1
5
1
list1 = [1.976662114355723e-81, -1.449552217194197e-81]
2
list2 = [2.8808538131862966, 2.0268679389242448]
3
list3 = [10.0, 6.799051318681892]
4
list4 = [115.48659741294217, 115.4865974120957]
5
I am trying to find a way to do it by including the key, for example to have an index form 1 to 2 and do string matching with "Pbat_ch["+str(index)+"]"
. Any better idea of how to achieve that?
Advertisement
Answer
As your “indices” are always in order and consecutive, use a simple collection in a defaultdict after reworking the key:
JavaScript
1
9
1
from collections import defaultdict
2
3
out = defaultdict(list)
4
5
for k,v in dic.items():
6
out[k.rsplit('[', 1)[0]].append(v)
7
8
out = dict(out)
9
output:
JavaScript
1
5
1
{'Pbat_ch': [1.976662114355723e-81, -1.449552217194197e-81],
2
'Pbat_dis': [2.8808538131862966, 2.0268679389242448],
3
'Ebat': [10.0, 6.799051318681892],
4
'Pgrid': [115.48659741294217, 115.4865974120957]}
5
accessing a given sublist:
JavaScript
1
3
1
out['Pbat_ch']
2
# [1.976662114355723e-81, -1.449552217194197e-81]
3
Or as list of lists:
JavaScript
1
7
1
list(out.values())
2
3
[[1.976662114355723e-81, -1.449552217194197e-81],
4
[2.8808538131862966, 2.0268679389242448],
5
[10.0, 6.799051318681892],
6
[115.48659741294217, 115.4865974120957]]
7