【问题标题】:How to access an object within a list of them?如何访问它们列表中的对象?
【发布时间】:2021-02-19 15:20:05
【问题描述】:

所以我有一个来自 API 的对象列表,如下所示:

{
    "1": {
        "artist": "Ariana Grande",
        "title": "Positions"
    },
    "2": {
        "artist": "Luke Combs",
        "title": "Forever After All"
    },
    "3": {
        "artist": "24kGoldn Featuring iann dior",
        "title": "Mood"
    },
}

我想知道如何运行for 循环来访问每个项目。

def create_new_music_chart(data_location):
    with open(data_location, 'r') as json_file:
        data = json.load(json_file)

for song in data:
    print(song)
 
Returns:
```
1
2
3

但是当我尝试这样做来打印艺术家时,它不起作用:

for song in data:
    print(song[artist])

结果:

TypeError: string indices must be integers

【问题讨论】:

  • 试试print(data[song]['artist'])

标签: python json loops object


【解决方案1】:

song 是字典中的键。如果要获取艺术家,则必须在字典data中查找关键字song,而artist应该是一个字符串:

for song in data:
    # song is "1"
    # data[song] is {"artist": "Ariana Grande", "title": "Positions"}
    print(data[song]["artist"])

【讨论】:

    【解决方案2】:

    song 是键,而不是字典值。改为使用values 进行迭代:

    for song_dict in data.values():
        print(song_dict["artist"])
    

    【讨论】:

    • 哦,我以前从未真正考虑过这种方式,谢谢。对未来非常有用。
    猜你喜欢
    • 2017-01-10
    • 1970-01-01
    • 2021-05-24
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多