Skip to main content
 首页 » 编程设计

python之将数据访问到字典 python 列表中

2025年02月15日9JustinYoung

我有一个字典列表,里面有一些嵌套的字典:

[{'id': '67569006', 
'kind': 'analytics#accountSummary', 
'name': 'Adopt-a-Hydrant', 
'webProperties': [{'id': 'UA-62536006-1', 
                 'internalWebPropertyId': '102299473', 
                 'kind': 'analytics#webPropertySummary', 
                 'level': 'STANDARD', 
                 'name': 'Adopt-a-Hydrant', 
                 'profiles': [{'id': '107292146', 
                               'kind': 'analytics#profileSummary', 
                               'name': 'Adopt a Hydrant view1', 
                               'type': 'WEB'}, 
                              {'id': '1372982608', 
                               'kind': 'analytics#profileSummary', 
                               'name': 'Unfiltered view', 
                               'type': 'WEB'}], 
                 'websiteUrl': 'https://example1.com/'}]}, 
{'id': '44824959', 
'kind': 'analytics#accountSummary', 
'name': 'Adorn', 
'webProperties': [{'id': 'UA-62536006-1', 
                 'internalWebPropertyId': '75233390', 
                 'kind': 'analytics#webPropertySummary', 
                 'level': 'STANDARD', 
                 'name': 'Website 2', 
                 'profiles': [{'id': '77736192', 
                               'kind': 'analytics#profileSummary', 
                               'name': 'All Web Site Data', 
                               'type': 'WEB'}], 
                 'websiteUrl': 'http://www.example2.com'}]}, 
] 

我正在尝试打印网站名称、网址和 View ,如果该网站有 2 个或更多 View ,则将它们全部打印出来,这就是它变得棘手的地方。

到目前为止我已经尝试过:

all_properties = [The list above] 
for single_property in all_properties: 
    single_propery_name=single_property['name'] 
    view_name=single_property['webProperties'][0]['profiles'][0]['name'] 
    view_id=single_property['webProperties'][0]['profiles'][0]['id'] 
    print(single_propery_name, view_name, view_id) 

这几乎可以工作,但它只打印每个属性的第一个 View profile>name,但是有些属性有多个 View ,我还需要这些 View 才能打印出来。

现在的输出是:

Adopt-a-Hydrant Adopt a Hydrant view1 107292146 
Website 2 All Web Site Data 77736192 

所以它跳过了第一个属性的第二个 View 。我尝试嵌套一个子 for 循环,但我无法让它工作,最终输出应该是:

Adopt-a-Hydrant Adopt a Hydrant view1 107292146 
Adopt-a-Hydrant Unfiltered View 1372982608 
Website 2 All Web Site Data 77736192 

关于如何获得它的任何想法?

请您参考如下方法:

您需要遍历每个 single_property 的配置文件列表:

for single_property in all_properties: 
    single_property_name = single_property['name'] 
    for profile in single_property['webProperties'][0]['profiles']: 
            view_name = profile['name'] 
            view_id = profile['id'] 
            print(single_property_name, view_name, view_id) 

如果您阅读 python docs 中的内容可能会有所帮助关于列表以及如何遍历它们