Home > OS >  nested loop to a dict, in order to turn into a json?
nested loop to a dict, in order to turn into a json?

Time:10-03

I have a nest loop like so:

prices = [[1,2,3,4],[3,4,1,2]]

That I would like to turn into a dict structure in order to form into a json using json.dumps, so for example:

prices = [{apple:1,banana:2,pear:3,orange:4},{apple:3,banana:4,pear:1,orange:2}]
prices_json = json.dumps(prices)

however I'm having trouble due to the nested loop structure. One idea I had was to iterate through the loop using map(), and then using zip to form a dict per inner loop

def prices_to_dict(prices):
    price_headers=['apple','banana','pear','orange']
    return dict(zip(price_headers,prices))
prices_dict_list=map(prices_to_dict,prices)
prices_json = json.dumps(prices_dict_list)

but this doesn't seem to work the way I'd like, and isn't returning anything

Is there a better way to handle this? or a better way to name the columns inside this loop and then pop it into a json file?

CodePudding user response:

Use a dict comprehension and a list comprehension:

prices = [[1, 2, 3, 4], [3, 4, 1, 2]]
price_headers = ['apple', 'banana', 'pear', 'orange']

out = [{key: val for key, val in zip(price_headers, price)} for price in prices]
print(out)

# Output
[{'apple': 1, 'banana': 2, 'pear': 3, 'orange': 4},
 {'apple': 3, 'banana': 4, 'pear': 1, 'orange': 2}]
import json

jout = json.dumps(out, indent=4)
print(jout)

# Output:
[
    {
        "apple": 1,
        "banana": 2,
        "pear": 3,
        "orange": 4
    },
    {
        "apple": 3,
        "banana": 4,
        "pear": 1,
        "orange": 2
    }
]

CodePudding user response:

Go through each list in prices then zip it with fruits and add it to temp dictionary then append it result list.

prices = [[1,2,3,4],[3,4,1,2]]
fruits = ['apple','banana','pear','orange']
res = []

for price in prices:
    temp = {}
    for k,v in zip(fruits, price):
        temp.update({k:v})
    res.append(temp)

prices_json = json.dumps(res)
print(prices_json)

Gives output

[{"apple": 1, "banana": 2, "pear": 3, "orange": 4}, {"apple": 3, "banana": 4, "pear": 1, "orange": 2}]
  • Related