Python中Dict的价值

时间:2017-12-16 13:41:09

标签: python dictionary

我有一个代码来从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)

2 个答案:

答案 0 :(得分: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'}

答案 1 :(得分: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)