如何删除字典的前几行?

时间:2019-02-10 21:39:23

标签: python-3.x

这是我的代码

# Our search function
def ndb_search(q):
    """Returns terms regarding food's foodgroup, name, NBD number, data source, and manufacturer from the USDA Food Composition Databases based on your 'q'"""
    response = requests.get("https://api.nal.usda.gov/ndb/search", params = {
        'api_key': key,
        'q': q,
        'offset': 0,
        'fg': "",
        'name': "",
        'ndbno': "",
        'ds': "",
        'manu': ""
    })
    # Checks if we get a HTTP status code back
    response.raise_for_status()
    # Converts out JSON format information into lists and dictionaries
    search_output = response.json()
    return search_output

ndb_search("quail eggs")

这是我得到的输出: Output I get

这是我想要的输出: Output I want

如果有帮助,这是我要操作的字典:

search_ output = {'list': {'q': 'quail eggs', 'sr': '1', 'ds': 'any', 'start': 0, 'end': 6, 'total': 6, 'group': '', 'sort': 'r', 'item': [{'offset': 0, 'group': 'Branded Food Products Database', 'name': 'EL COMPI, QUAIL EGGS, UPC: 854955002226', 'ndbno': '45362205', 'ds': 'LI', 'manu': "milly's desserts llc"}, {'offset': 1, 'group': 'Branded Food Products Database', 'name': 'BUDDHA, QUAIL EGGS IN BRINE, UPC: 761934535098', 'ndbno': '45099560', 'ds': 'LI', 'manu': 'Sung Ly International Corporation'}, {'offset': 2, 'group': 'Branded Food Products Database', 'name': 'GRAN SABANA, QUAIL EGGS, UPC: 819140010103', 'ndbno': '45169279', 'ds': 'LI', 'manu': 'L & M C Farms, Inc.'}, {'offset': 3, 'group': 'Branded Food Products Database', 'name': 'L&W, QUAIL EGGS, UPC: 024072000256', 'ndbno': '45094890', 'ds': 'LI', 'manu': 'L&W International Co.'}, {'offset': 4, 'group': 'Branded Food Products Database', 'name': 'CHAOKOH, QUAIL EGG IN BRINE, UPC: 044738074186', 'ndbno': '45094707', 'ds': 'LI', 'manu': 'Theppadung Porn Coconut Co'}, {'offset': 5, 'group': 'Dairy and Egg Products', 'name': 'Egg, quail, whole, fresh, raw', 'ndbno': '01140', 'ds': 'SR', 'manu': 'none'}]}}

3 个答案:

答案 0 :(得分:1)

好像您只想要“ item”一样,因此您可以使用以下命令进行访问:output['list']['item']

答案 1 :(得分:1)

search_output.get('list',{}).get('item',[])

假设search_output是一个字典,那么此行将获取列表字典中的项目列表。如果由于某种原因您在列表中没有列表或项目集合,则此语句将仅返回一个空列表。这可以根据api.nal.usda.gov上API的实现方式来实现。

答案 2 :(得分:0)

要从字典中获取项目,可以使用项目查找(如列表中的索引)。 它的工作原理完全相同,只接受您拥有的任何密钥类型(密钥必须是可哈希的):

my_dict = {'str': 1, type: lambda:None, 5: 'five'}
my_dict['str'], my_dict[type], my_dict[5]  # 1, <lambda at #???>, 'five'

这也适用于任何深度:

my_deep_dict = {1: {'k': [{'x': 3}]}}
my_deep_dict[1]['k'][0]['x']   # 3

对于您而言,只需使用search_output['list']['item']