遍历字典 python

Looping over dictionary python

我正在学习这个 yelp API 教程:http://letstalkdata.com/2014/02/how-to-use-the-yelp-api-in-python/

我有下面的代码。我基本上是在尝试以一种有意义的方式分离出结果词典的元素。现在我只得到一整条数据流......我如何以这样一种方式循环遍历字典,使其一个接一个地干净地呈现所有键和值?

import rauth
import time

def main():
    locations = [(39.98,-82.98),(42.24,-83.61),(41.33,-89.13)]
    api_calls = []
    for lat,long in locations:
        params = get_search_parameters(lat,long)
        api_calls.append(get_results(params))
        #Be a good internet citizen and rate-limit yourself
        time.sleep(1.0)

    ##Do other processing

    for key in api_calls:
        print key

def get_results(params):

    #Obtain these from Yelp's manage access page
    consumer_key = "CONSUMER_KEY_HERE"
    consumer_secret = "CONSUMER_SECRET_HERE"
    token = "TOKEN_HERE"
    token_secret = "TOKEN_SECRET_HERE"

    session = rauth.OAuth1Session(
        consumer_key = consumer_key
        ,consumer_secret = consumer_secret
        ,access_token = token
        ,access_token_secret = token_secret)

    request = session.get("http://api.yelp.com/v2/search",params=params)

    #Transforms the JSON API response into a Python dictionary
    data = request.json()
    session.close()

    return data

def get_search_parameters(lat,long):
    #See the Yelp API for more details
    params = {}
    params["term"] = "restaurant"
    params["ll"] = "{},{}".format(str(lat),str(long))
    params["radius_filter"] = "2000"
    params["limit"] = "10"

    return params

if __name__=="__main__":
    main()

我不确定您希望结果采用哪种格式。如果您需要包含字典中的结果,您可以将它们附加到 api 调用,然后将它们与您的密钥一起打印。

或者,您可以试试这个:

for idx,key in enumerate(api_calls):
    #This will print out the order and the value
    print ("{}: {}".format(idx,key)) 

api_calls 是一个字典列表。每个字典都有一个键 businesses,它引用了一个字典列表,一个对应于该位置的每个企业。

您想遍历 API 个调用结果列表。对于每个条目,遍历企业列表并打印键 namephone

的值
for location in api_calls:
     for business in location['businesses']:
         print business['name'], business['phone']

输出:

Creole Kitchen 6143723333
Los Potosinos 6148876895
Royal Fish, Shrimp, & Chicken 6144296002
Shades Restaurant 6142916555
Zanzibar Brews 6147580111
Grass Skirt Tiki Room 6144293650
That Food Truck 6149463797
Los Potosinos 6148876895
Asian Wok II 6142527661
Cafe On Long 6142524552
Beezy's 7344859625
Sidetrack 7344831035
The Bomber Restaurant 7344820550
Maìz Mexican Cantina 7343406010
Bona Sera Cafe 7343406335
Red Rock Downtown Barbecue 7343402381
The Wurst Bar 7344856720
ABC Microbrewery 7344802739
Cafe Ollie 7344828050
Aubree's Pizzeria & Grill 7344838888
Brandys 8152201744
Mark Allen's American Kitchen 8152200642
Bayou Express 8157808651
Demilio's Italian Deli 8152244808
Fourth Street Bakery & Cafe 8152241927
Peru Pizza House Restaurant 8152237408
Right Spice Supper Club 8152239824
Maples Supper Club the 8152231938
Liberty Family Restaurant 8152243240
Pizzas by Marchelloni 8152201564