Sort dictionary by another dictionary

I had a problem sorting 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 view a list and

  • From each dictionary, create a new list containing items from the dictionary. ( It depends on what elements and how many elements need to be added to the list when the user makes this choice )
  • sort list

When I say sorting, I intend to create 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 sorts each list according to the values ​​in the order dictionary.


During one of the script execution, all lists may 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 may 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 can I make a list of specific values ​​from a dictionary and sort it by values ​​in another dictionary that has the same keys as the first dictionary?

Evaluate any ideas / suggestions, sorry for the noobish behavior - I'm still learning python / programming

+4
source share
1 answer

The first field of the code contains invalid Python syntax (I suspect that the d = parts are extraneous ...?), And it is also unreasonable to trample the built-in name list .

In any case, this 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 great way to get the desired result ['thisfile.flt', 'box', '8.7', '10.5', '2.2', "red.jpg'] :

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

All Articles