我有eg p_deck={3:12, 5:23, 6:8, 9:47, 10:18}需要p_deck={0:12, 1:23, 2:8, 3:47, 4:18}最有效的方法是什么?我试着:
p_deck={3:12, 5:23, 6:8, 9:47, 10:18}
p_keys_list=[]
p_values_list=[]
p_length=0
def order():
global p_keys_list
global p_values_list
global p_length
p_keys_list=p_deck.keys()
p_values_list=p_deck.values()
p_length=len(p_deck)
p_deck={}
for i in p_length:
p_deck[i]={p_keys_list[i]:p_values_list[i]}
return
但是这会导致错误。也许你可以解决这个问题,但是,这种试图把字典拆散然后使其更有序的方法是不是太笨拙了?我是一个新手,似乎找不到符合这个基本水平的常见问题解答。
您不是在尝试排序,而是在重新定义键。
你可以使用:
p_deck = dict(enumerate(p_deck.values()))
输出:
{0: 12, 1: 23, 2: 8, 3: 47, 4: 18}
注意,如果您需要键始终是插入的顺序,那么字典可能不是最佳选择。不如使用列表:
p_deck = list(p_deck.values())
p_deck[0]
# 12
p_deck[4]
# 18
p_deck={3:12, 5:23, 6:8, 9:47, 10:18}
p_keys_list=[]
# create a list out of your dictionary using the first element of the list as the key
for i in p_deck.keys():
p_keys_list.append([i, p_deck[i]])
# sort p_keys_list
p_keys_list.sort(key=lambda x: x[0])
# transform it back into a dictionary
p_deck = dict(p_keys_list)