Python中Dict的价值

问题描述 投票:-3回答:2

我有一个代码来从Yahoo API获取特定值。问题是它与IF语句匹配,但它返回None,并且由于某种原因它再次返回到else循环。我是python的新手。

我希望得到关键天文学的价值作为回报。

import requests
def walk(d = None,val = None):

    if val == 'astronomy':
        return (val,d)

    else:

        for k,v in d.items():
            if isinstance(v,dict):
                p = d[k]
                walk(d=p,val=k)

r = requests.get('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22nome%2C%20ak%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys',stream = True)

n = r.json()
b = walk(d=n)
print(b)
python dictionary
2个回答
1
投票

没有必要拿起密钥或只是为了取出值来进行递归调用 - 只要你的数据嵌套在字典中的字典中,你只需要递归迭代它们的值,直到你找到一个包含你的值。键:

import requests

def find_value(data, key):
    if key in data:
        return data[key]
    for v in data.values():
        if isinstance(v, dict):
            v = find_value(v, key)
            if v is not None:
                return v

r = requests.get(
    'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast'
    '%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D'
    '%22nome%2C%20ak%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys',
    stream=True)

n = r.json()
b = find_value(n, "astronomy")
print(b)  # {'sunset': '3:57 pm', 'sunrise': '11:58 am'}

0
投票

你正在递归,所以当它找到astronomy时,它只会从该回调返回到循环中。您需要测试函数的返回值并使用它。例如:

import requests
def walk(d = None,val = None):

    print("val:", val)
    if val == 'astronomy':
        return (val,d)

    else:

        for k,v in d.items():
            if isinstance(v,dict):
                p = d[k]
                rtn = walk(d=p,val=k)       # Changed
                if not rtn is None:         # Added
                    return rtn              # Added

r = requests.get('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22nome%2C%20ak%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys',stream = True)

n = r.json()
b = walk(d=n)
print(b)
© www.soinside.com 2019 - 2024. All rights reserved.