AnswerBun.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!

Related Questions

Why NCat overs immediately if I call it by Popen?

1  Asked on February 9, 2021 by shkiperdesna

         

Understanding Generic Class implementation

3  Asked on February 9, 2021 by yeo

   

full join of the several data frames of nested data frame

2  Asked on February 9, 2021 by seyed-hosseini

     

JSON file in Index.html

0  Asked on February 9, 2021 by maria-rodriguez

   

Spring boot nested native sql query is not working

1  Asked on February 8, 2021 by shivam-kumar

       

How to access array outside of a function in javascript

1  Asked on February 8, 2021 by hamza-sayyid

       

Close PyQt Dialog without closing main programme

2  Asked on February 8, 2021 by gilly4297

       

Make a loop within for loop statement in Python

4  Asked on February 8, 2021 by papemoussa

       

Need help formatting pandas data frame from json file

2  Asked on February 8, 2021 by soscodehelp

     

regex with bs4 is splitting the results

1  Asked on February 8, 2021 by edison

     

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir