TransWikia.com

How to Iterate 'Values' of a Nested Dictionary from a Nested Dictionary

Stack Overflow Asked by PSK on September 25, 2020

{'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}]}

I want the value of key A to be printed as below may be by using forloop or something like that:

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

2 Answers

You can iterate over the dict, look for the desired key and concatenate its value:

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 = "")

OUTPUT:

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

Correct answer by DirtyBit on September 25, 2020

you can create another dict with thise items:

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)

output:

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

Answered by ylj ylj on September 25, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP