How to merge key values within dictionaries if they have a common key-value pair?
<p>I have a list of dictionaries,</p>

<pre><code>list = [
    {'hostname': 'a', 'ipaddr':'abcde'},
    {'hostname': 'a', 'ipaddr':'fghijkl'},
    {'hostname': 'a', 'ipaddr':'bbbbbb'},
    {'hostname': 'b', 'ipaddr':'xxxx'}
]
</code></pre>

<p>How do I make it so that the output looks like this:</p>

<pre><code>outputList = [
    {
        'hostname': 'a',
        'ipaddr': ['abcde', 'fghijkl', 'bbbbbb']
    },
    {
        'hostname': 'b',
        'ipaddr':'xxxx'
    }
]
</code></pre>

<hr>

<p><strong>Edit</strong>:
Before this step, I have filtered a JSON list of selected hostnames </p>

<pre><code>['hostname1', 'hostname2', 'hostname3', 'hostname4' ......]
</code></pre>

<p>Then, given a huge JSON list of dictionaries (called "list" above), I have to sieve out the respective hostnames and ipaddresses, preferably grouped according to hostnames so that I can parse it elsewhere easily. </p>

<p>You can use below code:</p>

<pre><code>list_1 = [
{'hostname': 'a', 'ipaddr':'abcde'},
{'hostname': 'a', 'ipaddr':'fghijkl'},
{'hostname': 'a', 'ipaddr':'bbbbbb'},
{'hostname': 'b', 'ipaddr':'xxxx'}
]

out_list = []

for each_dict in list_1:
    if out_list:
        for out_dict in out_list:
            if out_dict['hostname']==each_dict['hostname']:
                out_dict['ipaddr'].append(each_dict['ipaddr'])
            else:
                temp_dict = {}
                temp_dict['hostname']=each_dict['hostname']
                temp_dict['ipaddr']=[each_dict['ipaddr'],]
                out_list.append(temp_dict)
    else:
        temp_dict = {}
        temp_dict['hostname']=each_dict['hostname']
        temp_dict['ipaddr']=[each_dict['ipaddr'],]
        out_list.append(temp_dict)

print out_list
</code></pre>

python list dictionary merge