Issue
I have the following dictionary:
My_dict={'K0A1': 0.12, 'K1A1': 0.12, 'K2A1': 0.12, 'K3A1': 0.12, 'K0A2': 0.16, 'K1A2': 0.16, 'K2A2': 0.16, 'K3A2': 0.16, 'K0A3': 0.04, 'K1A3': 0.04, 'K2A3': 0.04, 'K3A3': 0.04, 'K0B1': 0.04, 'K1B1': 0.04, 'K2B1': 0.04, 'K3B1': 0.04, 'K0B2': 0.08, 'K1B2': 0.08, 'K2B2': 0.08, 'K3B2': 0.08, 'K0B3': 0.04, 'K1B3': 0.04, 'K2B3': 0.04, 'K3B3': 0.04, 'K0C1': 0.08, 'K1C1': 0.08, 'K2C1': 0.08, 'K3C1': 0.08, 'K0C2': 0.04, 'K1C2': 0.04, 'K2C2': 0.04, 'K3C2': 0.04, 'K0C3': 0.04, 'K1C3': 0.04, 'K2C3': 0.04, 'K3C3': 0.04, 'K0D1': 0.08, 'K1D1': 0.08, 'K2D1': 0.08, 'K3D1': 0.08, 'K0D2': 0.08, 'K1D2': 0.08, 'K2D2': 0.08, 'K3D2': 0.08, 'K0D3': 0.12, 'K1D3': 0.12, 'K2D3': 0.12, 'K3D3': 0.12}
I want to extract values of K0A1, K0A2,K0A3 in a separate list. Similary for K0B1,K0B2,K0B3 and so on until the end. How do I do it? Can anyone please suggest a solution
Solution
If you want to group all subdictionnary by the second and third character of the key (you can actually use any other function if the logic is different), you could use a nested defaultdict
:
from collections import defaultdict
d = defaultdict(lambda:defaultdict(dict))
for k,v in My_dict.items():
d[k[1:3]][k] = v
out = {k: dict(v) for k,v in d.items()}
Output:
{'0A': {'K0A1': 0.12, 'K0A2': 0.16, 'K0A3': 0.04},
'1A': {'K1A1': 0.12, 'K1A2': 0.16, 'K1A3': 0.04},
'2A': {'K2A1': 0.12, 'K2A2': 0.16, 'K2A3': 0.04},
'3A': {'K3A1': 0.12, 'K3A2': 0.16, 'K3A3': 0.04},
'0B': {'K0B1': 0.04, 'K0B2': 0.08, 'K0B3': 0.04},
'1B': {'K1B1': 0.04, 'K1B2': 0.08, 'K1B3': 0.04},
'2B': {'K2B1': 0.04, 'K2B2': 0.08, 'K2B3': 0.04},
'3B': {'K3B1': 0.04, 'K3B2': 0.08, 'K3B3': 0.04},
'0C': {'K0C1': 0.08, 'K0C2': 0.04, 'K0C3': 0.04},
'1C': {'K1C1': 0.08, 'K1C2': 0.04, 'K1C3': 0.04},
'2C': {'K2C1': 0.08, 'K2C2': 0.04, 'K2C3': 0.04},
'3C': {'K3C1': 0.08, 'K3C2': 0.04, 'K3C3': 0.04},
'0D': {'K0D1': 0.08, 'K0D2': 0.08, 'K0D3': 0.12},
'1D': {'K1D1': 0.08, 'K1D2': 0.08, 'K1D3': 0.12},
'2D': {'K2D1': 0.08, 'K2D2': 0.08, 'K2D3': 0.12},
'3D': {'K3D1': 0.08, 'K3D2': 0.08, 'K3D3': 0.12}}
To access a single subgroup:
out['0A']
# {'K0A1': 0.12, 'K0A2': 0.16, 'K0A3': 0.04}
alternative output
from collections import defaultdict
d = defaultdict(list)
for k,v in My_dict.items():
d[k[:3]].append(v)
out=dict(d)
Output:
{'K0A': [0.12, 0.16, 0.04],
'K1A': [0.12, 0.16, 0.04],
'K2A': [0.12, 0.16, 0.04],
'K3A': [0.12, 0.16, 0.04],
'K0B': [0.04, 0.08, 0.04],
'K1B': [0.04, 0.08, 0.04],
'K2B': [0.04, 0.08, 0.04],
'K3B': [0.04, 0.08, 0.04],
'K0C': [0.08, 0.04, 0.04],
'K1C': [0.08, 0.04, 0.04],
'K2C': [0.08, 0.04, 0.04],
'K3C': [0.08, 0.04, 0.04],
'K0D': [0.08, 0.08, 0.12],
'K1D': [0.08, 0.08, 0.12],
'K2D': [0.08, 0.08, 0.12],
'K3D': [0.08, 0.08, 0.12]}
Answered By - mozway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.