Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Any alternative approaches to format in a list of dictionaries?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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']}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading