Sort multiple dictionaries identically, based on a specific order defined by a list
<p>I had a special case where multiple existing dictionaries had to be sorted based on the exact order of items in a list (not alphabetical). So for example the dictionaries were:</p>

<pre><code>dict_one = {"LastName": "Bar", "FirstName": "Foo", "Address": "Example Street 101", "Phone": "012345678"}
dict_two = {"Phone": "001122334455", "LastName": "Spammer", "FirstName": "Egg", "Address": "SSStreet 123"}
dict_three = {"Address": "Run Down Street 66", "Phone": "0987654321", "LastName": "Biker", "FirstName": "Random"}
</code></pre>

<p>And the list was:</p>

<pre><code>data_order = ["FirstName", "LastName", "Phone", "Address"]
</code></pre>

<p>With the expected result being the ability to create a file like this:</p>

<pre><code>FirstName;LastName;Phone;Address
Foo;Bar;012345678;Example Street 101
Egg;Spammer;001122334455;SSStreet 123
Random;Biker;0987654321;Run Down Street 66
</code></pre>

<p><strong>Note</strong>:
In my case, the real use was an Excel file using pyexcel-xls, but the CSV-like example above is probably closer to what is usually done, so the answers might be more universally applicable for CSV than Excel.</p>

<p>I had a bit of hard time to find any good answers in Stack Overflow for this case, but eventually I got the sorting working, which I could use to create the file. The header row can simply be taken directly from the <code>data_order</code> list below. Here's how I did it - hope it helps someone:</p>

<pre><code>from collections import OrderedDict
import pprint

dict_one = {
    "LastName": "Bar", 
    "FirstName": "Foo", 
    "Address": "Example Street 101", 
    "Phone": "012345678"}
dict_two = {
    "Phone": "001122334455", 
    "LastName": "Spammer", 
    "FirstName": "Egg", 
    "Address": "SSStreet 123"}  
dict_three = {
    "Address": "Run Down Street 66", 
    "Phone": "0987654321", 
    "LastName": "Biker", 
    "FirstName": "Random"}

dict_list = []
dict_list.append(dict_one)
dict_list.append(dict_two)
dict_list.append(dict_three)

data_order = ["FirstName", "LastName", "Phone", "Address"]

result = []
for dictionary in dict_list:
    result_dict = OrderedDict()
    # Go through the data_order in order
    for key in data_order:
        # Populate result_dict in the list order
        result_dict[key] = dictionary[key]
    result.append(result_dict)

pp = pprint.PrettyPrinter(indent=4)
pp.pprint(result)
"""
[   {   'FirstName': 'Foo',
        'LastName': 'Bar',
        'Phone': '012345678',
        'Address': 'Example Street 101'},
    {   'FirstName': 'Egg',
        'LastName': 'Spammer',
        'Phone': '001122334455',
        'Address': 'SSStreet 123'},
    {   'FirstName': 'Random',
        'LastName': 'Biker',
        'Phone': '0987654321',
        'Address': 'Run Down Street 66'}]
"""
</code></pre>

python python-3.x sorting