def get_first_key(dictionary):
for key in dictionary:
return key
raise IndexError
first_key = get_first_key(colors)
first_val = colors[first_key]
如果您需要 n-th 键,那么类似地
def get_nth_key(dictionary, n=0):
if n < 0:
n += len(dictionary)
for i, key in enumerate(dictionary.keys()):
if i == n:
return key
raise IndexError("dictionary index out of range")
def key_at_index(mydict, index_to_find):
for index, key in enumerate(mydict.keys()):
if index == index_to_find:
return key
return None # the index doesn't exist
查找键的索引:
def index_of_key(mydict, key_to_find):
for index, key in enumerate(mydict.keys()):
if key == key_to_find:
return index
return None # the key doesn't exist