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>This can be achieved in a one liner, although it is harder to read. In case it is useful for someone:</p>

<pre><code>print [OrderedDict([(key, d[key]) for key in data_order]) for d in [dict_one, dict_two, dict_three]]
</code></pre>

python python-3.x sorting