如何从嵌套字典创建包含子字典键的列表?

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

形成嵌套字典,如何创建包含子字典键的列表?

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

需要如下结果:

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

您可以使用 keys:

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

(其实可以省略.keys()!)

如果您不能假设嵌套字典具有相同的键,但您希望得到包含所有唯一键的结果,您可以遍历每个嵌套字典并实现集合联合,如下所示:

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

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