Generate list of values from nested dictionary as values


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?

Asked By: Noorulain Islam



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()}
Answered By: blhsing

@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}}

for k, v in d.items():

#{'A': ['A', 'C', 'D'], 'B': ['B', 'C']}
Answered By: God Is One
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.