Python, list of nested repeated keys

Question:

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.

Asked By: Dejan Skolegi

||

Answers:

Here is one way to do it in a less complicated manner:

# data = {"data": ...}

chains = sum([[i['CU']] + [j['chain'] for j in i['CO']] for i in data['data']], [])
print(chains)

# Output:
# ['AGLD', 'ERC20', 'SCT', 'SOL', 'BBF', 'ERC20', 'ACH', 'ERC20', 'BEP20', 'ISP', 'ERC20', 'BEP20', 'ACK', 'BEP20']
Answered By: LTJ

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.

Answered By: furas
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.