Python嵌套字典列表的递归遍历

def list_dictionary(d, n_tab=-1):
    if isinstance(d, list):
        for i in d:
            list_dictionary(i, n_tab)
    elif isinstance(d, dict):
        n_tab+=1
        for key, value in d.items():
            print("{}key:{}".format("\t"*n_tab, key))
            list_dictionary(value, n_tab)
    else:
        print("{}{}".format("\t"*n_tab, d))
data = {"info": "成绩单",
        "grades": {
            "Chinese":
                [{"小明": 60}, {"小红": 80}],
            "Math":
                [{"小明": 90}, {"小红": 70}],
            "English":
                [{"小明": 80}, {"小红": 80}],
        }}
list_dictionary(data)
key:info
成绩单
key:grades
	key:Chinese
		key:小明
		60
		key:小红
		80
	key:Math
		key:小明
		90
		key:小红
		70
	key:English
		key:小明
		80
		key:小红
		80

参考文献1中只能跑嵌套字典,稍微改进了一下

参考文献

  1. python嵌套字典的递归遍历

你可能感兴趣的:(Python)