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>

<pre><code>from collections import defaultdict

lst = [
    {'hostname': 'a', 'ipaddr':'abcde'},
    {'hostname': 'a', 'ipaddr':'fghijkl'},
    {'hostname': 'a', 'ipaddr':'bbbbbb'},
    {'hostname': 'b', 'ipaddr':'xxxx'}
]

d = defaultdict(list)

for item in lst:
    d[item['hostname']].append(item['ipaddr'])

output = [dict(zip(['hostname', 'ipaddr'], item)) for item in d.items()]
</code></pre>

python list dictionary merge