Home > database >  How to convert each value in a dictionary to a separate list?
How to convert each value in a dictionary to a separate list?

Time:04-13

So I'm trying to convert the values in in payload to a separate list. The first value of fruits, I'm trying to place that in the fruits list and the same with the vegetables.


main.py

import requests

headers = {
  'Content-Type': 'application/json'
}

list_of_fruits = ["orange", "banana", "mango"]
list_of_vegetables = ["squash", "brocoli", "aspharagus"]

payload = {
    "fruits": list_of_fruits
    "vegetables": list_of_vegetables
}

response = requests.post(f"127.1.1.1:9000/json", headers=headers, json=payload)

------------------------------------------------------------------------------------------

flask_api.py

from flask import Flask, request

@app.route('/post_json', methods=['POST'])
def process_json():
    content_type = request.headers.get('Content-Type')
    if (content_type == 'application/json'):
        
        fruits= [] 
        vegetables = []
         
        data = request.json
        for k, v in data.items(): #How can I convert the first list of values to the fruits list? and the same for vegetables?
            print(v) ---> ["orange", "banana", "mango"]["squash", "brocoli", "aspharagus"]
        
        return data
    else:
        return 'Content-Type not supported!'

#Output ---> ["orange", "banana", "mango"]["squash", "brocoli", "aspharagus"]

CodePudding user response:

you need to read the data from request. your request is in form somehting like this

{
   'fruits': ['list of fruits'],
   'vegetables': ['list of vegetables']

}

you are reading request data in json format using data = requests.json, which is of same format as above mentioned.

now to read/save the data in list, you need to read the data from data dictionary and save it in list.

fruits = data.get('fruits', []) # [] in case no 'fruits' as key value in payload
vegetables = data.get('vegetables', [])

Here fruits and vegetables are list you save your data.

  • Related