Search code examples
python-3.xlistkeyordereddictionary

python return list of sorted dictionary keys


I'm sure this has been asked and answered, but I cant find it. I have this dictionary:

{'22775': 15.9, 
 '22778': 29.2, 
 '22776': 20.25, 
 '22773': 9.65, 
 '22777': 22.9, 
 '22774': 12.45}

a string and a float.

I want to list the key strings in a tk listbox to allow the user to select one and then use the corresponding float in a calculation to determine a delay factor in an event.

I have this code:

def dic_entry(line):
    #Create key:value pairs from string
    key, sep, value = line.strip().partition(":")
    return key, float(value)

with open(filename1) as f_obj:    
    s = dict(dic_entry(line) for line in f_obj)
print (s) #for testing only
s_ord = sorted(s.items(),key=lambda x: x[1])
print (s_ord)

The first print gets me

{'22775': 15.9, 
 '22778': 29.2, 
 '22776': 20.25, 
 '22773': 9.65, 
 '22777': 22.9, 
 '22774': 12.45}

as expected. The second, which I hoped would give me an ordered list of keys gets me

[('22773', 9.65), 
 ('22774', 12.45), 
 ('22775', 15.9), 
 ('22776', 20.25), 
 ('22777', 22.9), 
 ('22778', 29.2)].

I have tried using sorteddictionary from the collections module and it gives me a sorted dictionary, but I'm having trouble extracting a list of keys.

s_ord2 = []
for keys in s.items():  
  s_ord2.append (keys)
print (s_ord2)

gives me a list of key value pairs:

[('22776', 20.25), 
 ('22777', 22.9), 
 ('22774', 12.45), 
 ('22773', 9.65), 
 ('22778', 29.2), 
 ('22775', 15.9)]

I'm sure I'm doing something dumb, I just don't know what it is.


Solution

  • You're using items when you want to use keys:

    In [1]: d = {'z': 3, 'b': 4, 'a': 9}
    
    In [2]: sorted(d.keys())
    Out[2]: ['a', 'b', 'z']
    
    In [3]: sorted(d.items())
    Out[3]: [('a', 9), ('b', 4), ('z', 3)]
    

    d.items() gives you tuples of (key, value); d.keys() just gives you just the keys.