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>Here is one way:</p>

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

outputList = {}
for d in inputList:
    od = outputList.setdefault(d['hostname'], {})
    od.setdefault('hostname', d['hostname'])
    od.setdefault('ipaddr', []).append(d['ipaddr'])
outputList = sorted(outputList.values(), key=lambda x: x['hostname'])

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

python list dictionary merge