简体   繁体   中英

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

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

You can use keys :

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

(Actually you can omit .keys() !)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM