Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :


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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading