首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从Python中的另一个函数中的一个函数访问值列表?

从Python中的另一个函数中的一个函数访问值列表?
EN

Stack Overflow用户
提问于 2018-06-23 11:17:52
回答 2查看 170关注 0票数 0

我有一个收集UPC列表的函数。我创建了另一个函数来获取列表并搜索价格。我遇到的问题是,当找不到UPC时,就会发生KeyError。如何忽略不匹配的UPC并继续执行代码?当前版本的代码是一个无限循环。

代码语言:javascript
复制
def trending():
    trending = requests.get('http://api.com/trends?format=json&apiKey={}'.format(apiKey))
    trendingResponse = trending.json()
    items = trendingResponse['items']

    for item in items:
        price = item['salePrice']
        name = item['name']
        upc = item['upc']
        stock = item['stock']
        image = item['largeImage']
        url = item['productUrl']
        sDescription = item['shortDescription']
        brandName = item['brandName']
        availableOnline = item['availableOnline']

        print('Current UPC = ' + str(upc))
        return upc_lookup(upc)

def upc_lookup(upc):
    products_api = mws.Products(access_key, secret_key, seller_id, region='US')
    # lookup product by upc
    products = products_api.get_matching_product_for_id(marketplaceid=marketplace_usa, type_='UPC', ids=upc)
    parse = products.parsed

    while True:
        try:
            # return asin from UPC lookup
            asin = parse['Products']['Product']['Identifiers']['MarketplaceASIN']['ASIN']['value']
            print('ASIN Found = ' + str(asin))
        except KeyError:
            print('UPC {} not Found in Amazon'.format(upc))
EN

回答 2

Stack Overflow用户

发布于 2018-06-23 11:53:30

看起来我不得不将第一个函数中的返回值移出For循环。

票数 0
EN

Stack Overflow用户

发布于 2018-06-23 12:03:37

代码语言:javascript
复制
def function_1():
    function_1.item = {'sale-Price':100, 'name':'ABC', 'stock':3, 'brand-name':4}`

def function_2():
    item = function_1.item
    sp = item['salePrice']
    name = item['name']
    stock = item['stock']
    print(sp, name, stock)

function_1()
function_2()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50997647

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档