Consolidate python dictionary list
<p>Original python dictionary list:</p>

<pre><code>    [
     {"keyword": "nike", "country":"usa"},
     {"keyword": "nike", "country":"can"},
     {"keyword": "newBalance", "country":"usa"},
     {"keyword": "newBalance", "country":"can"}
    ]
</code></pre>

<p>I would like to consolidate the python dict list and get an output like:</p>

<pre><code>    [
     {"keyword": "nike", "country":["usa","can"]},
     {"keyword": "newBalance", "country":["usa","can"]}
    ]
</code></pre>

<p>What is the most efficient way to do this?</p>

<pre><code>L = [
     {"keyword": "nike", "country":"usa"},
     {"keyword": "nike", "country":"can"},
     {"keyword": "newBalance", "country":"usa"},
     {"keyword": "newBalance", "country":"can"}
    ]


def consolidate(L):
    answer = {}
    for d in L:
        if d['keyword'] not in answer:
            answer['keyword'] = set()
        answer['keyword'].add(d['country'])

    retval = []
    for k,countries in answer.items():
        retval.append({'keyword':d['keyword'], 'country':list(countries)})
    return retval
</code></pre>

python python-2.7