axaxa
axaxa

Reputation: 3

How to merge key values within dictionaries if they have a common key-value pair?

I have a list of dictionaries,

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

How do I make it so that the output looks like this:

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

Edit: Before this step, I have filtered a JSON list of selected hostnames

['hostname1', 'hostname2', 'hostname3', 'hostname4' ......]

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.

Upvotes: 0

Views: 751

Answers (4)

Sergey Gornostaev
Sergey Gornostaev

Reputation: 7807

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()]

Upvotes: 0

Mahendra Gaur
Mahendra Gaur

Reputation: 390

You can use below 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

Upvotes: 0

Wasi
Wasi

Reputation: 1492

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

hostnames = set([d['hostname'] for d in lists])

outputlist= list()

for hostname in hostnames:
    od = {
        'hostname': hostname,
        'ipaddr': []
        }
    for d in lists:
        if d['hostname'] == hostname:
            od['ipaddr'].append(d['ipaddr'])
    outputlist.append(od)

This solution assumes that all the dictionaries inside lists will contain the key 'hostname'.

Upvotes: 1

Robᵩ
Robᵩ

Reputation: 168876

Here is one way:

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']
    }
]

Upvotes: 1

Related Questions