比如字典:
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]))