Search code examples
pythonlistnestedkey

Python, list of nested repeated keys


I would like to process this json data in python:

{"data":
   [{"CU":"AGLD","CO": [{"chain":"ERC20"}],                 "fn":"Adventure Gold"}, 
    {"CU":"ACH","CO":  [{"chain":"ERC20"},    {"chain":"BEP20"}],   "fn":"Alchemy"}]}
    

I would like to get the value of all "chain"s. For example like this:

CU  chains:
AGLD    ERC20
ACH     ERC20
ACH     BEP20

I tried with a for loop, but (in the case of several "chain"s) it returns only the last value of "chain" for example ACH BEP20. Does not return ACH ERC20.


Solution

  • You said you used for-loop but you need neested for-loops - like this:

    data = {"data": [
        {"CU":"AGLD", "CO": [{"chain": "ERC20"}],                    "fn":"Adventure Gold"}, 
        {"CU":"ACH",  "CO": [{"chain": "ERC20"}, {"chain":"BEP20"}], "fn":"Alchemy"}
    ]}
    
    for item in data['data']:
        for subitem in item['CO']:
            print(item['CU'], subitem['chain'])
    

    Result:

    AGLD ERC20
    ACH ERC20
    ACH BEP20    
    

    BTW:

    You didn't show how you keep it but if you keep in dictionary then you need list to keep all values result[key] = [value1, value2]. If you will assing result[key] = value then you get only last item.