Ian
Ian

Reputation:

sort dictionary by another dictionary

I've been having a problem with making sorted lists from dictionaries. I have this list

list = [
    d = {'file_name':'thisfile.flt', 'item_name':'box', 'item_height':'8.7', 'item_width':'10.5', 'item_depth':'2.2', 'texture_file': 'red.jpg'},
    d = {'file_name':'thatfile.flt', 'item_name':'teapot', 'item_height':'6.0', 'item_width':'12.4', 'item_depth':'3.0' 'texture_file': 'blue.jpg'},
    etc.
]

I'm trying to loop through the list and

When I say sort, I imagine creating a new dictionary like this

order = {
    'file_name':    0,
    'item_name':    1, 
    'item_height':  2,
    'item_width':   3,
    'item_depth':   4,
    'texture_file': 5
}

and it sorts each list by the values in the order dictionary.


During one execution of the script all the lists might look like this

['thisfile.flt', 'box', '8.7', '10.5', '2.2']
['thatfile.flt', 'teapot', '6.0', '12.4', '3.0']

on the other hand they might look like this

['thisfile.flt', 'box', '8.7', '10.5', 'red.jpg']
['thatfile.flt', 'teapot', '6.0', '12.4', 'blue.jpg']

I guess my question is how would I go about making a list from specific values from a dictionary and sorting it by the values in another dictionary which has the same keys as the first dictionary?

Appreciate any ideas/suggestions, sorry for noobish behaviour - I am still learning python/programming

Upvotes: 7

Views: 6709

Answers (1)

Alex Martelli
Alex Martelli

Reputation: 881555

The first code box has invalid Python syntax (I suspect the d = parts are extraneous...?) as well as unwisely trampling on the built-in name list.

Anyway, given for example:

d = {'file_name':'thisfile.flt', 'item_name':'box', 'item_height':'8.7', 
     'item_width':'10.5', 'item_depth':'2.2', 'texture_file': 'red.jpg'}

order = {
    'file_name':    0,
    'item_name':    1, 
    'item_height':  2,
    'item_width':   3,
    'item_depth':   4,
    'texture_file': 5
}

one nifty way to get the desired result ['thisfile.flt', 'box', '8.7', '10.5', '2.2', "red.jpg'] would be:

def doit(d, order):
  return  [d[k] for k in sorted(order, key=order.get)]

Upvotes: 12

Related Questions