在数组中追加多个值

Append multiple values in a array

'我正在尝试从 Hubspot 获取交易数据,我正在尝试在此示例中获取 dealid 和交易名称以简化问题,但稍后我将提供更多属性。我有以下代码,它为我提供了一组 dealIds 和一组交易名称。我可以做到这一点,而不是多个数组,而是得到以下内容:

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

或类似的东西:

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

到目前为止,这是我的代码:

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'])

AS E.Serra 建议 deal_obj = {'dealname': properties['dealname']['value'], 'dealid':deal['dealId']} 解决了这个问题。

这是更新后的代码:

%%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)

您已经拥有 json 中的数据。这正是您想要映射和存储它的方式。

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']})

这可以使用列表理解来解决:

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