如何从嵌套字典迭代嵌套字典的“值”

时间:2020-08-17 12:20:12

标签: python-3.x dictionary

{'value1': [{"A":100, "B":2}], ‘value2’: [{"A":1, "B":2},{"A":2, "B":4},{"A":3, "B":2},{"A":4, "B":4}], ‘value3’: [{"A":10}]}

我希望通过使用forloop或类似的东西来打印键A的值,如下所示:

value1 = 100 , Value2 = 1,2,3,4, value3 = 10

2 个答案:

答案 0 :(得分:0)

您可以遍历该字典,查找所需的key并连接其值:

dd = {'value1': [{"A":100, "B":2}], 'value2': [{"A":1, "B":2},{"A":2, "B":4},{"A":3, "B":2},{"A":4, "B":4}], 'value3': [{"A":10}]}

res = []
for k,v in dd.items():
    s = ''
    for elem in v:
        for kk,vv in elem.items():
            if kk == 'A':
                s += str(elem[kk]) + ', '
    # print(k, s)
    res.append([k,s])

for e in res:
    print(" = ".join(e), end = "")

输出:

value1 = 100, value2 = 1, 2, 3, 4, value3 = 10, 

答案 1 :(得分:0)

您可以使用此项目创建另一个字典:

a = {'value1': [{"A":100, "B":2}], 'value2': [{"A":1, "B":2},{"A":2, "B":4},{"A":3, 

"B":2},{"A":4, "B":4}], 'value3': [{"A":10}]}
list1 = []
b = {}
for k,v in a.items():
    for x in v:
        list1.append(x["A"])
    b[k] = list1
    list1 = []
print(b)

输出:

{'value1': [100], 'value2': [1, 2, 3, 4], 'value3': [10]}