Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何访问它们列表中的对象?_Python_Json_Loops_Object - Fatal编程技术网

Python 如何访问它们列表中的对象?

Python 如何访问它们列表中的对象?,python,json,loops,object,Python,Json,Loops,Object,我有一个API中的对象列表,如下所示: { "1": { "artist": "Ariana Grande", "title": "Positions" }, "2": { "artist": "Luke Combs", "title&quo

我有一个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

歌曲
是字典中的关键。如果您想获得艺术家,必须在字典
数据
中查找键
歌曲
,并且
艺术家
应该是一个字符串:

对于歌曲输入数据:
#歌曲是“1”
#资料[歌曲]是{“艺术家”:“阿里亚娜·格兰德”,“标题”:“职位”}
打印(数据[歌曲][“艺术家”])

歌曲
是关键,而不是字典值。使用
值进行迭代

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

试试打印(数据[歌曲][艺术家])
哦,我以前从未考虑过这种方式,谢谢。对未来非常有用。