首页 > 解决方案 > Python 3 - 列表和字典

问题描述

考虑到下面显示的 google maps API 输出,我尝试使用 Python dict 方法获取值,但出现错误消息:"AttributeError: 'list' object has no attribute 'values'"

{
    "address_components": [
        {
            "long_name": "1",
            "short_name": "1",
            "types": [
                "street_number"
            ]
        },
        {
            "long_name": "Amphitheatre Parkway",
            "short_name": "Amphitheatre Pkwy",
            "types": [
                "route"
            ]
        },
        {
            "long_name": "Mountain View",
            "short_name": "Mountain View",
            "types": [
                "locality",
                "political"
            ]
        },
        {
            "long_name": "Santa Clara County",
            "short_name": "Santa Clara County",
            "types": [
                "administrative_area_level_2",
                "political"
            ]
        },
        {
            "long_name": "California",
            "short_name": "CA",
            "types": [
                "administrative_area_level_1",
                "political"
            ]
        },
        {
            "long_name": "United States",
            "short_name": "US",
            "types": [
                "country",
                "political"
            ]
        },
        {
            "long_name": "94043",
            "short_name": "94043",
            "types": [
                "postal_code"
            ]
        },
        {
            "long_name": "1326",
            "short_name": "1326",
            "types": [
                "postal_code_suffix"
            ]
        }
    ],
    "formatted_address": "1 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
    "geometry": {
        "location": {
            "lat": 37.4268042,
            "lng": -122.0806179
        },
        "location_type": "ROOFTOP",
        "viewport": {
            "northeast": {
                "lat": 37.4281531802915,
                "lng": -122.0792689197085
            },
            "southwest": {
                "lat": 37.4254552197085,
                "lng": -122.0819668802915
            }
        }
    },
    "place_id": "ChIJZeH1dve5j4AR0RvMuo9xdlk",
    "plus_code": {
        "compound_code": "CWG9+PQ Mountain View, California, United States",
        "global_code": "849VCWG9+PQ"
    },
    "types": [
        "street_address"
    ]
}

这是我使用的代码:

results = gmaps.reverse_geocode((37.4267861, -122.0806032))
out = list(results.values())
print(out)

print(type(results))当我使用我在结果变量中查找类型时,它是一个列表。<class 'list'>.如果我在上面的输出中有键和值,为什么它被认为是一个列表而不是一个字典?

我已经阅读了 Python 中 List 和 Dict 之间的区别,其中一个正是 Dict 是无序的并且有一对 [key][value] 和 Lists 是有序的,并且您可以使用索引访问值。

从上述结果中获得例如“United States”和“CA”的最佳方法是什么?

干杯,

标签: pythonpython-3.xlistdictionary

解决方案


如果results是您在问题开头打印的输出,则无需尝试 go getresults.values()更不用说将其放入另一个列表中。

results可能是一个包含字典的列表(尽管当我查看您的数据时它肯定看起来不在列表中)。你的字典里有列表。

您可以访问特定值,例如:

print(results[0]["address_components"][3]["types"][1]) # should print 'political'

你也可以试试这个:

for r in results:              # Loop over all items in the list `results`
    for key, val in r.items(): # Loop over all key value pairs in `r`
        print(key)             # Print key
        # Whatever you want to do here

否则,您可以通过简单地运行打印一个 json 格式的树:

import json
print(json.dumps(results, indent=4))

或者,如果您想制作更紧凑的列表,请尝试以下递归函数:

def parse(data, indent=0):
    if not isinstance(data, list):
        data = [data]

    for d in data:
        if not isinstance(d, dict):
            print(" "*4*indent + d)
            continue

        for key, val in d.items():
            if isinstance(val, list) or isinstance(val, dict):
                print("{}{}" .format(
                    " "*4*indent, key))
                parse(val, indent + 1)
            else:
                print("{}{}{}{}" .format(
                    " "*4*indent, key, " "*(38-len(key)-4*indent), val))

parse(results)

最后一个解决方案为您提供以下输出:

address_components
    long_name                         1
    short_name                        1
    types
        street_number
    long_name                         Amphitheatre Parkway
    short_name                        Amphitheatre Pkwy
    types
        route
    long_name                         Mountain View
    short_name                        Mountain View
    types
        locality
        political
    long_name                         Santa Clara County
    short_name                        Santa Clara County
    types
        administrative_area_level_2
        political
    long_name                         California
    short_name                        CA
    types
        administrative_area_level_1
        political
    long_name                         United States
    short_name                        US
    types
        country
        political
    long_name                         94043
    short_name                        94043
    types
        postal_code
    long_name                         1326
    short_name                        1326
    types
        postal_code_suffix
formatted_address                     1 Amphitheatre Pkwy, Mountain View, CA 94043, USA
geometry
    location
        lat                           37.4268042
        lng                           -122.0806179
    location_type                     ROOFTOP
    viewport
        northeast
            lat                       37.4281531802915
            lng                       -122.0792689197085
        southwest
            lat                       37.4254552197085
            lng                       -122.0819668802915
place_id                              ChIJZeH1dve5j4AR0RvMuo9xdlk
plus_code
    compound_code                     CWG9+PQ Mountain View, California, United States
    global_code                       849VCWG9+PQ
types
    street_address

推荐阅读