如何在列表中获取字典和嵌套字典的值?

时间:2015-01-28 20:25:48

标签: python dictionary

example_dict = [({'Progrm':'Python'},
                 {'Rohit':{'age':24,'pincode':400000}},
                 {'Rahul':{'age':22,'pincode':500000}})]

我想将上面的程序输出仅作为dict和嵌套字典的值:

Python
age:24, pincode : 400000
24
400000
age:22, pincode : 500000
22
500000

如何访问这些值?

1 个答案:

答案 0 :(得分:0)

example_dict是一个单元素列表,所以:

the_tuple = example_dict[0] # ({'Progrm':'Python'}, ...)
for dct in the_tuple:
    for value in dct.values():
        if isinstance(value, dict):
            print(", ".join(["{}:{}".format(k,v) for k,v in value.items()]))
            for v in value.values():
                print(v)
        else:
            print(value)

结果:

Python
age:24, pincode:400000
24
400000
age:22, pincode:500000
22
500000

或者更可笑:

"\n".join(["\n".join([", ".join(["{}:{}".format(k,v) for k,v in value.items()])]+[str(v) for v in value.values()]) if isinstance(value, dict) else value for tup in example_dict for dct in tup for value in dct.values()])