python - 如何使用 Python 打印嵌套字典中的特定整数变量?

标签 python dictionary nested

这是我的第一个问题:)

我循环嵌套字典来打印特定值。我正在使用以下代码。

for i in lizzo_top_tracks['tracks']:
    print('Track Name: ' + i['name'])

它适用于字符串变量,但不适用于其他变量。例如,当我对日期变量使用以下代码时:

for i in lizzo_top_tracks['tracks']:
    print('Album Release Date: ' + i['release_date'])

我收到类似这样的消息 KeyError: 'release_date'

我应该做什么?

这是我的嵌套字典的示例:

{'tracks': [{'album': {'album_type': 'album',
    'artists': [{'external_urls': {'spotify': 'https://open.spotify.com/artist/56oDRnqbIiwx4mymNEv7dS'},
      'href': 'https://api.spotify.com/v1/artists/56oDRnqbIiwx4mymNEv7dS',
      'id': '56oDRnqbIiwx4mymNEv7dS',
      'name': 'Lizzo',
      'type': 'artist',
      'uri': 'spotify:artist:56oDRnqbIiwx4mymNEv7dS'}],
    'external_urls': {'spotify': 'https://open.spotify.com/album/74gSdSHe71q7urGWMMn3qB'},
    'href': 'https://api.spotify.com/v1/albums/74gSdSHe71q7urGWMMn3qB',
    'id': '74gSdSHe71q7urGWMMn3qB',
    'images': [{'height': 640,
      'width': 640}],
    'name': 'Cuz I Love You (Deluxe)',
    'release_date': '2019-05-03',
    'release_date_precision': 'day',
    'total_tracks': 14,
    'type': 'album',
    'uri': 'spotify:album:74gSdSHe71q7urGWMMn3qB'}]}

最佳答案

您发布的代码在语法上不正确;通过 Python 解释器运行它会在最后一行出现语法错误。看起来你在最后的某个地方失去了一个大括号。 :)

我浏览了它并修复了空白以使结构更容易看到;您的格式化方式使得很难看出哪些键处于哪个嵌套级别,但是通过一致的缩进,它会变得更加清晰:

lizzo_top_tracks = {
    'tracks': [{
        'album': {
            'album_type': 'album',
            'artists': [{
                'external_urls': {
                    'spotify': 'https://open.spotify.com/artist/56oDRnqbIiwx4mymNEv7dS'
                },
                'href': 'https://api.spotify.com/v1/artists/56oDRnqbIiwx4mymNEv7dS',
                'id': '56oDRnqbIiwx4mymNEv7dS',
                'name': 'Lizzo',
                'type': 'artist',
                'uri': 'spotify:artist:56oDRnqbIiwx4mymNEv7dS'
            }],
            'external_urls': {
                'spotify': 'https://open.spotify.com/album/74gSdSHe71q7urGWMMn3qB'
            },
            'href': 'https://api.spotify.com/v1/albums/74gSdSHe71q7urGWMMn3qB',
            'id': '74gSdSHe71q7urGWMMn3qB',
            'images': [{'height': 640, 'width': 640}],
            'name': 'Cuz I Love You (Deluxe)',
            'release_date': '2019-05-03',
            'release_date_precision': 'day',
            'total_tracks': 14,
            'type': 'album',
            'uri': 'spotify:album:74gSdSHe71q7urGWMMn3qB'
        }
    }]
}

因此,您在 lizzo_top_tracks['tracks'] 中为 i 获得的第一个(也是唯一的)值将是这个字典:

i = {
    'album': {
        'album_type': 'album',
        'artists': [{
            'external_urls': {
                'spotify': 'https://open.spotify.com/artist/56oDRnqbIiwx4mymNEv7dS'
             },
            'href': 'https://api.spotify.com/v1/artists/56oDRnqbIiwx4mymNEv7dS',
            'id': '56oDRnqbIiwx4mymNEv7dS',
            'name': 'Lizzo',
            'type': 'artist',
            'uri': 'spotify:artist:56oDRnqbIiwx4mymNEv7dS'
        }],
        'external_urls': {
            'spotify': 'https://open.spotify.com/album/74gSdSHe71q7urGWMMn3qB'
        },
        'href': 'https://api.spotify.com/v1/albums/74gSdSHe71q7urGWMMn3qB',
        'id': '74gSdSHe71q7urGWMMn3qB',
        'images': [{'height': 640, 'width': 640}],
        'name': 'Cuz I Love You (Deluxe)',
        'release_date': '2019-05-03',
        'release_date_precision': 'day',
        'total_tracks': 14,
        'type': 'album',
        'uri': 'spotify:album:74gSdSHe71q7urGWMMn3qB'
    }
}

此字典中的唯一键是'album',其值是包含所有其他信息的另一个字典。例如,如果您想打印专辑发行日期和艺术家姓名列表,您可以这样做:

for track in lizzo_top_tracks['tracks']:
    print('Album Release Date: ' + track['album']['release_date'])
    print('Artists: ' + str([artist['name'] for artist in track['album']['artists']]))

如果这些是您自己构建的字典,您可能需要删除一些只有一个键的嵌套层,因为它们只会使您更难以在不提供任何附加信息的情况下导航结构。例如:

lizzo_top_albums = [{
    'album_type': 'album',
    'artists': [{
        'external_urls': {
            'spotify': 'https://open.spotify.com/artist/56oDRnqbIiwx4mymNEv7dS'
        },
        'href': 'https://api.spotify.com/v1/artists/56oDRnqbIiwx4mymNEv7dS',
        'id': '56oDRnqbIiwx4mymNEv7dS',
        'name': 'Lizzo',
        'type': 'artist',
        'uri': 'spotify:artist:56oDRnqbIiwx4mymNEv7dS'
    }],
    'external_urls': {
        'spotify': 'https://open.spotify.com/album/74gSdSHe71q7urGWMMn3qB'
    },
    'href': 'https://api.spotify.com/v1/albums/74gSdSHe71q7urGWMMn3qB',
    'id': '74gSdSHe71q7urGWMMn3qB',
    'images': [{'height': 640, 'width': 640}],
    'name': 'Cuz I Love You (Deluxe)',
    'release_date': '2019-05-03',
    'release_date_precision': 'day',
    'total_tracks': 14,
    'type': 'album',
    'uri': 'spotify:album:74gSdSHe71q7urGWMMn3qB'
}]

此结构允许您按照最初尝试的方式编写查询:

for album in lizzo_top_albums:
    print('Album Release Date: ' + album['release_date'])
    print('Artists: ' + str([artist['name'] for artist in album['artists']]))

简单多了,对吧? :)

关于python - 如何使用 Python 打印嵌套字典中的特定整数变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58683192/

相关文章:

python - 多个 Pandas 数据框的交集

python - 删除所有行和标题为 na 的数据框列

python - 从文件中读取时间戳并转换为 ms

python - 包含键中项目的字典中所有值的总和

c - 需要 build 一个金字塔,数字和星星之间有空格

java - 遍历集合时如何防止嵌套同步块(synchronized block)

c++ - 嵌套的 if 语句 C++

python - 使用 SqlAlchemy 执行原始查询(在 SQL-Server 数据库和 Pymssql 上)时,传递的参数无法识别并引发 SQL 错误

javascript - 使用 Google map javascript 计算距我的路径或 KML/KMZ 的两点距离

python - 使用 bool 键值对将字符串转换为字典格式