比如字典:

my_dict = {
    "first_key": 'first_value',
    "second_key": "second_value",
    "third_key": "third_value",
}

如果使用:

print(my_dict.keys()[0])
print(my_dict.values()[0])

这会导致报错:

TypeError: 'dict_keys' object is not subscriptable
TypeError: 'dict_values' object is not subscriptable

选取第一个元素

my_dict = {
    "first_key": 'first_value',
    "second_key": "second_value",
    "third_key": "third_value",
}

print("first key : ", next(iter(my_dict)))
print("first value : ", my_dict.get(next(iter(my_dict))))

选取最后一个元素

print("last key : ", list(my_dict.keys())[-1])
print("last value : ", my_dict.get(list(my_dict.keys())[-1]))
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐