Home > OS >  How to create a List containing a sub dictionary keys , from nested dictionary?
How to create a List containing a sub dictionary keys , from nested dictionary?

Time:05-15

Form nested dictionary, How to Create a List, containing Sub dictionary keys?

    dict_lbl = {
    "lbl1":{"name":"label1","item1":"Accounts",   "item2":"kannagu",    "shortcut":"F1","printitem":"You clicked label1"},
    "lbl2":{"name":"label2","item1":"Inventory",  "item2":"Saragu",     "shortcut":"F2","printitem":"You clicked label2"},
    "lbl3":{"name":"label3","item1":"Manufacture","item2":"Thayarippu", "shortcut":"F3","printitem":"You clicked label3"},
    "lbl4":{"name":"label4","item1":"PayRoll",    "item2":"Sambalam",   "shortcut":"F4","printitem":"You clicked label4"}
}

Need Result as follows:

['name', 'item1', 'item2', 'shortcut', 'printitem']

CodePudding user response:

You can use keys:

output = list(dict_lbl['lbl1'].keys())
print(output) # ['name', 'item1', 'item2', 'shortcut', 'printitem']

(Actually you can omit .keys()!)

CodePudding user response:

If you can't assume nested dictionaries have the same keys yet you want to have a result including all unique keys, you can iterate through each nested dictionary and implement set union like this:

list(set().union(*[d.keys() for d in dict_lbl.values()]))

>>> ['item1', 'printitem', 'name', 'shortcut', 'item2']
  • Related