Print Value of Key in Lists of Dicts in Python
<p>I am trying to print the value of a specific key in a list of dicts:</p>

<p>eg:</p>

<pre><code>list = [{'a' : 123, 'b': 'xyz', 'c': [1,2]}, {'a' : 456, 'b': 'cde', 'c': [3,4]}] 
</code></pre>

<p>I was hoping to be able to print the following for each dict:</p>

<pre><code>print ("a: ", a)
print ("b: ", b)
</code></pre>

<p>If you're guaranteed those keys exist, a nice solution using <a href="https://docs.python.org/3/library/operator.html#operator.itemgetter" rel="nofollow"><code>operator.itemgetter</code></a>:</p>

<pre><code>from operator import itemgetter

# Renamed your list; don't name variables list
for a, b in map(itemgetter('a', 'b'), mylist):
    print("a:", a)
    print("b:", b)
</code></pre>

<p>The above is just a slightly optimized version of the import free code, pushing the work of fetching values to the builtins instead of doing it over and over yourself.</p>

<pre><code>for d in mylist:  # Renamed your list; don't name variables list
    print("a:", d['a'])
    print("b:", d['b'])
</code></pre>

<p>Oh, and for completeness (Aaron Hall is right that it's nice to avoid redundant code), a tweak to <code>itemgetter</code> usage to observe DRY rules:</p>

<pre><code>keys = ('a', 'b')
for values in map(itemgetter(*keys), mylist):
    for k, v in zip(keys, values):
        print(k, v, sep=": ")
</code></pre>

python dictionary