Home > Blockchain >  Any alternative approaches to format in a list of dictionaries?
Any alternative approaches to format in a list of dictionaries?

Time:11-28

I have a list of dictionaries:

data = [
    {"id": 55, "name": "Ram", "city": "kathmandu"},
    {"id": 66, "name": "Hari", "city": "lalitpur"},
    {"id": 77, "name": "Sita", "city": "kathmandu"},
    {"id": 88, "name": "Geeta", "city": "pokhara"},
    {"id": 99, "name": "Shyam", "city": "pokhara"},
    {"id": 95, "name": "Parbati", "city": "bhaktapur"}
]

I want the expected output as:

{'kathmandu': ['Ram', 'Sita'], 'lalitpur': ['Hari'], 'pokhara': ['Shyam', 'Geeta'], 'bhaktapur': ['Parbati']}

My solution is:

for i in data:
    i[i.get('city')] = i['name']
    del i['name']
    del i['id']
    del i['city']
    
new_data = data[::-1]

first_dict = dict((key, val) for k in data for key, val in k.items())
second_dict = dict((key, val) for k in new_data for key, val in k.items())
for key in first_dict:
    if key in second_dict:
        new_list = [first_dict[key],second_dict[key]]
        new_list2 = list(set(new_list))
        second_dict[key] = new_list2
        
c = {**first_dict, **second_dict}

print(c)

This produced the desired results. But, I want to know any alternative approaches for this solution.

CodePudding user response:

You can use setdefault:

result={}
for di in data:
    result.setdefault(di['city'], []).append(di['name'])

>>> result
{'kathmandu': ['Ram', 'Sita'], 'lalitpur': ['Hari'], 'pokhara': ['Geeta', 'Shyam'], 'bhaktapur': ['Parbati']}

CodePudding user response:

You have a working solution, but you are modifying the dict in place and completely reshaping it. I'd recommend just putting the data you need in new_dict.

Looks like a job for defaultdict.

data = [
    {"id": 55, "name": "Ram", "city": "kathmandu"},
    {"id": 66, "name": "Hari", "city": "lalitpur"},
    {"id": 77, "name": "Sita", "city": "kathmandu"},
    {"id": 88, "name": "Geeta", "city": "pokhara"},
    {"id": 99, "name": "Shyam", "city": "pokhara"},
    {"id": 95, "name": "Parbati", "city": "bhaktapur"}
]

from collections import defaultdict

new_data = defaultdict(list)
for record in data:
    city = record['city']
    name = record['name']
    new_data[city].append(name)

print(new_data)
  • Related