Extract all keys from a list of dictionaries
<p>I'm trying to get a list of all keys in a list of dictionaries in order to fill out the fieldnames argument for csv.DictWriter.</p>

<p>previously, I had something like this: </p>

<pre><code>[
{"name": "Tom", "age": 10},
{"name": "Mark", "age": 5},
{"name": "Pam", "age": 7}
]
</code></pre>

<p>and I was using <code>fieldnames = list[0].keys()</code> to take the first dictionary in the list and extract its keys.</p>

<p>Now I have something like this where one of the dictionaries has more key:value pairs than the others (could be any of the results).  The new keys are added dynamically based on information coming from an API so they may or may not occur in each dictionary and I don't know in advance how many new keys there will be.</p>

<pre><code>[
{"name": "Tom", "age": 10},
{"name": "Mark", "age": 5, "height":4},
{"name": "Pam", "age": 7}
]
</code></pre>

<p>I can't just use <code>fieldnames = list[1].keys()</code> since it isn't necessarily the second element that will have extra keys.</p>

<p>A simple solution would be to find the dictionary with the greatest number of keys and use it for the fieldnames, but that won't work if  you have an example like this: </p>

<pre><code>[
{"name": "Tom", "age": 10},
{"name": "Mark", "age": 5, "height":4},
{"name": "Pam", "age": 7, "weight":90}
]
</code></pre>

<p>where both the second and third dictionary have 3 keys but the end result should really be the list <code>["name", "age", "height", "weight"]</code></p>
