Skip to content
Advertisement

Iterate through dict with keys being strings with index

I have a dictionary in the following form:

dic = {
    "Pbat_ch[1]": 1.976662114355723e-81,
    "Pbat_ch[2]": -1.449552217194197e-81,
    "Pbat_dis[1]": 2.8808538131862966,
    "Pbat_dis[2]": 2.0268679389242448,
    "Ebat[1]": 10.0,
    "Ebat[2]": 6.799051318681892,
    "Pgrid[1]": 115.48659741294217,
    "Pgrid[2]": 115.4865974120957,
}

I need to get 4 lists of the following form:

list1 = [1.976662114355723e-81, -1.449552217194197e-81]
list2 = [2.8808538131862966, 2.0268679389242448]
list3 = [10.0, 6.799051318681892]
list4 = [115.48659741294217, 115.4865974120957]

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:

from collections import defaultdict

out = defaultdict(list)

for k,v in dic.items():
    out[k.rsplit('[', 1)[0]].append(v)

out = dict(out)

output:

{'Pbat_ch': [1.976662114355723e-81, -1.449552217194197e-81],
 'Pbat_dis': [2.8808538131862966, 2.0268679389242448],
 'Ebat': [10.0, 6.799051318681892],
 'Pgrid': [115.48659741294217, 115.4865974120957]}

accessing a given sublist:

out['Pbat_ch']
# [1.976662114355723e-81, -1.449552217194197e-81]

Or as list of lists:

list(out.values())

[[1.976662114355723e-81, -1.449552217194197e-81],
 [2.8808538131862966, 2.0268679389242448],
 [10.0, 6.799051318681892],
 [115.48659741294217, 115.4865974120957]]
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement