如何使用LOOP获取列表中每个字典的第一个键的值?

时间:2018-10-24 08:18:22

标签: python-3.x dictionary

示例代码:

dict1 = {"firstname":"Anna", "lastname":"Lupe", "ID":12000789}
dict2 = {"firstname":"Max", "lastname":"Mustermann", "ID":12345}

list_of_dict = [dict1, dict2]
print(list_of_dict)

输出:

[{'firstname': 'Anna', 'lastname': 'Lupe', 'ID': 12000789}, {'firstname': 'Max', 'lastname': 'Mustermann', 'ID': 12345}]

如何使用LOOP获取(打印)所有名字?说,像这样:

for el in list_of_dict:
    print el[0]

但是字典不支持索引...

1 个答案:

答案 0 :(得分:0)

使用dict.keys()获取字典键,然后将其转换为列表并获取第一个。

dict1 = {"firstname": "Anna", "lastname": "Lupe", "ID": 12000789}
dict2 = {"firstname": "Max", "lastname": "Mustermann", "ID": 12345}

list_of_dict = [dict1, dict2]
print(list_of_dict)

for el in list_of_dict:
    first_key = list(el.keys())[0]
    print(el[first_key])