简体   繁体   English

基本 python / 排序杂乱的字典

[英]basic python / sort messy dictionary

I have eg p_deck={3:12, 5:23, 6:8, 9:47, 10:18} and need p_deck={0:12, 1:23, 2:8, 3:47, 4:18} what is the most efficient way of doing it?我有例如 p_deck={3:12, 5:23, 6:8, 9:47, 10:18} 并且需要 p_deck={0:12, 1:23, 2:8, 3:47, 4:18最有效的方法是什么? I tried:我试过:

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

But this results in error.但这会导致错误。 It could be that you can solve this but then, is this method of trying to tease a dictionary apart and then reform it more orderly too unwieldy?可能你可以解决这个问题,但是,这种试图把字典拆开然后更有条理地改造它的方法是否太笨拙了? I can't seem to find a FAQ that matches this basic level as I am a newbie.由于我是新手,我似乎找不到与此基本级别相匹配的常见问题解答。

You're not trying to sort but rather to redefine the keys.您不是要排序,而是要重新定义键。

You can use:您可以使用:

p_deck = dict(enumerate(p_deck.values()))

Output: Output:

{0: 12, 1: 23, 2: 8, 3: 47, 4: 18}

Note that if you need your keys to always be the order of insertion, a dictionary might not be the best choice.请注意,如果您需要您的键始终是插入顺序,那么字典可能不是最佳选择。 Rather use a list:而是使用一个列表:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM