我有一个嵌套字典,它与描述的in this link非常相似。在
用户arainchi在那里发布了以下功能:
def findkeys(node, kv):
if isinstance(node, list):
for i in node:
for x in findkeys(i, kv):
yield x
elif isinstance(node, dict):
if kv in node:
yield node[kv]
for j in node.values():
for x in findkeys(j, kv):
yield x
如果我这么做
^{pr2}$将打印作为生成器对象类型的给定键的子级。在
当我试着列出keys()时
print ((findkeys(d, 'id')).keys())
我得到了
AttributeError: 'generator' object has no attribute 'keys'
我怎样才能拿到找回的孩子的钥匙?在
示例:
cfg_dict = { 'mobile' :
{ 'checkBox_OS' :
{ 'status' : 'None',
'radioButton_Andriod' :
{ 'status' : 'None',
'comboBox_Andriod_Brands' : 'LG'},
'radioButton_Windows' :
{ 'status' : 'None',
'comboBox_Windows_Brands' : 'Nokia'},
'radioButton_Others' :
{ 'status' : 'None',
'comboBox_Others_Brands' : 'Apple'}},
'checkBox_Screen_size' :
{ 'status' : 'None',
'doubleSpinBox_Screen_size' : '5.0' }}
}
print ("findkeys: ", findkeys(self.cfg_dict, "radioButton_Andriod"))
print ("list of findkeys:", list(findkeys(self.cfg_dict, "radioButton_Andriod")))
print ("keys of findKeys:", list(findkeys(self.cfg_dict, "radioButton_Andriod"))[0].keys())
输出:
findkeys: <generator object findkeys at 0x02F0C850>
list of findkeys: [{'status': False, 'comboBox_Andriod_Brands': 'Sony'}]
keys of findKeys: dict_keys(['status', 'comboBox_Andriod_Brands'])
我想迭代孩子的键。 有点像
#pseudo code
for everykey in child.keys()
if everykey.value == "this":
#do this
else:
#do that
找到第一个孩子的钥匙。如果不是dict,它会出错,因此您可能需要检查
编辑:对于你在新编辑中要求的内容
^{pr2}$相关问题 更多 >
编程相关推荐