Append multiple values in a array

508 Views Asked by At

'I am trying to fetch deals data from Hubspot, I am trying to fetch dealid and deal name in this example to simplify the question but later I will more properties. I have the following code that gives me an array of dealIds and one array of deal names. I could I make it that instead of multiple arrays I get the following instead:

{{12345,'deal1'}, {12346,'deal2'}, {12347,'deal3'}}

or something like:

{{'dealId': 12345, 'dealname' : 'deal1'}}

This is my code so far:

deals = []
names = []

def getdeals():
    apikey = "demo"
    url = 'https://api.hubapi.com/deals/v1/deal/paged?hapikey='+apikey+'&properties=dealname&limit=250'
    response = requests.get(url)
    jsonDeals = response.json()

    for deal in jsonDeals['deals']:
       properties = deal['properties']
       deals.append(deal['dealId'])
       names.append(properties['dealname']['value'])
3

There are 3 best solutions below

0
On BEST ANSWER

You already have the data in json. Its just how you want to map and store it.

output={}
def getdeals():
    apikey = "demo"
    url = 'https://api.hubapi.com/deals/v1/deal/paged?hapikey='+apikey+'&properties=dealname&limit=250'
    response = requests.get(url)
    jsonDeals = response.json()

    for deal in jsonDeals['deals']:
       properties = deal['properties']
       output.update({deal['dealId']: properties['dealname']['value']})
0
On

AS E.Serra suggested deal_obj = {'dealname': properties['dealname']['value'], 'dealid':deal['dealId']} solved the issue.

here is the updated code:

%%time
deals = []

def getdeals():
    apikey = "demo"
    url = 'https://api.hubapi.com/deals/v1/deal/paged?hapikey='+apikey+'&properties=dealname&limit=250'
    response = requests.get(url)
    jsonDeals = response.json()

    for deal in jsonDeals['deals']:
       properties = deal['properties']
       deal_obj = {'dealname': properties['dealname']['value'], 'dealid':deal['dealId']}
       deals.append(deal_obj)
0
On

This can be solved using list comprehension:

[{'dealId':deal['dealId'],'dealname':deal['properties']['dealname']['value']} for deal in jsonDeals['deals']]