我正在尝试编写一个字典密钥生成器,只有当密钥映射的值是list类型时才会生成密钥迭代器,使用递归和简单的isinstance
检查(我添加了一些打印)声明为了我自己的利益,因为我似乎无法运行这个东西):
def list_key_generator(inputDict):
for key in inputDict.keys():
if (isinstance(inputDict[key], dict)):
print ("Entering dict: %s " % key)
list_key_generator(inputDict[key])
elif (isinstance(inputDict[key], list)):
print ("Value is a list! key, value = %s, %s" % (key, inputDict[key]))
yield key
我必须误解yield
(不排除其他内容),因为完全相同的递归函数打印出键,完美运行:
def print_list_keys(inputDict):
for key in inputDict.keys():
if (isinstance(inputDict[key], list)):
print ("Value is a list! key, value = %s, %s" % (key, inputDict[key]))
elif (isinstance(inputDict[key], dict)):
print_list_keys(inputDict[key])
整个示例如下所示:
#!/usr/bin/python
def print_list_keys(inputDict):
for key in inputDict.keys():
if (isinstance(inputDict[key], list)):
print ("Value is a list! key, value = %s, %s" % (key, inputDict[key]))
elif (isinstance(inputDict[key], dict)):
print_list_keys(inputDict[key])
def list_key_generator(inputDict):
for key in inputDict.keys():
if (isinstance(inputDict[key], dict)):
print ("Entering dict: %s " % key)
list_key_generator(inputDict[key])
elif (isinstance(inputDict[key], list)):
print ("Value is a list! key, value = %s, %s" % (key, inputDict[key]))
yield key
def main():
inputDict = { "A" : { "x" : [0,1,2] , "y" : ["one", "two"] }, "B" : { "z" : ["one"] }, "C" : [9,8,7] }
print("Input dict : %s " % inputDict)
# Print list keys
print("print_list_keys : BEGIN")
print_list_keys(inputDict)
print("print_list_keys : END")
print("list_key_generator : BEGIN")
# Print all keys in the dict, whose values are lists.
for leafValue in list_key_generator(inputDict):
print (leafValue)
print("list_key_generator : END")
if (__name__ == "__main__"):
main()
我正在使用Python 3.4.1,这是输出:
Input dict : {'A': {'x': [0, 1, 2], 'y': ['one', 'two']}, 'C': [9, 8, 7], 'B': {'z': ['one']}}
print_list_keys : BEGIN
Value is a list! key, value = x, [0, 1, 2]
Value is a list! key, value = y, ['one', 'two']
Value is a list! key, value = C, [9, 8, 7]
Value is a list! key, value = z, ['one']
print_list_keys : END
list_key_generator : BEGIN
Entering dict: A
Value is a list! key, value = C, [9, 8, 7]
C
Entering dict: B
list_key_generator : END
答案 0 :(得分:1)
当你递归调用你的生成器时,你实际上不会迭代它们的结果。使用yield from
委托递归调用:
yield from list_key_generator(inputDict[key])
其他提示:
请勿致电.keys()
;你可以通过遍历字典本身迭代键:
for key in inputDict:
在Python中,使用if
进行测试时,不需要在表达式周围添加括号:
if isinstance(inputDict[key], dict):
您可以使用dict.items()
获取密钥和值:
def list_key_generator(d):
for key, value in d.items():
if isinstance(value, dict):
print("Entering dict:", key)
yield from list_key_generator(value)
elif isinstance(value, list):
print("Value is a list! key, value = {}, {}".format(key, value))
yield key