Home > Net >  basic python / sort messy dictionary
basic python / sort messy dictionary

Time:01-01

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? 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.

CodePudding user response:

You're not trying to sort but rather to redefine the keys.

You can use:

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

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

CodePudding user response:


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)
  • Related