Home > Software engineering >  Iterate through dict with keys being strings with index
Iterate through dict with keys being strings with index

Time:08-26

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?

CodePudding user response:

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]]

CodePudding user response:

If you really insist on having variables list1, list2, and so on:

from collections import defaultdict

dict_ = {
    "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,
}

lists = defaultdict(list)

for key, value in dict_.items():
    key = key[:key.find("[")]
    lists[key].append(value)

for i, value in enumerate(lists.values(), start=1):
    # exec is unsafe. Don't use with untrusted inputs.
    exec(f"list{i} = {value}")

# The lists are as expected
print(f"{list1=}")
print(f"{list2=}")
print(f"{list3=}")
print(f"{list4=}")

Output:

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