Generate list of values from nested dictionary as values
Question:
I have a nested dictionary like this:
d = {'A': {'A': 0.11, 'C': 0.12, 'D': 1.0}, 'B': {'B': 0.13, 'C': 0.14}}
I want to generate this output where in values only the list of keys of inner dictionary are selected.
output dictionary
output = {'A':['A', 'C', 'D'], 'B':['B', 'C']}
Is there any way to do?
Answers:
You can pass each sub-dict to the list
constructor to convert the keys to a list:
output = {k: list(v) for k, v in d.items()}
@blhsing’s answer is the way to go. This is also a way.
d = {'A': {'A': 0.11, 'C': 0.12, 'D': 1.0}, 'B': {'B': 0.13, 'C': 0.14}}
e={}
for k, v in d.items():
e[k]=list(v.keys())
print(e)
#{'A': ['A', 'C', 'D'], 'B': ['B', 'C']}
I have a nested dictionary like this:
d = {'A': {'A': 0.11, 'C': 0.12, 'D': 1.0}, 'B': {'B': 0.13, 'C': 0.14}}
I want to generate this output where in values only the list of keys of inner dictionary are selected.
output dictionary
output = {'A':['A', 'C', 'D'], 'B':['B', 'C']}
Is there any way to do?
You can pass each sub-dict to the list
constructor to convert the keys to a list:
output = {k: list(v) for k, v in d.items()}
@blhsing’s answer is the way to go. This is also a way.
d = {'A': {'A': 0.11, 'C': 0.12, 'D': 1.0}, 'B': {'B': 0.13, 'C': 0.14}}
e={}
for k, v in d.items():
e[k]=list(v.keys())
print(e)
#{'A': ['A', 'C', 'D'], 'B': ['B', 'C']}