Please give me a simple Python algorithm question!

Asked 2 years ago, Updated 2 years ago, 108 views

list = [{'id':'hello'','name':'kim','address':'seoul'},{'id:'hello','name':'choi','address':'busan'}]

If there's a dictionary on the list, If the id value is the same I want to combine the name and address, i.e.

list = [{'id':'hello'','name':['kim','choi'],'address':['seoul','busan']}] I want to make it like this, what should I do?

python algorithm list dictionary

2022-09-22 18:50

1 Answers

lst = [
    {'id':'hello','name':'kim','address':'seoul'},
    {'id':'hello','name':'choi','address':'busan'},
    {'id':'hey','name':'demi','address':'seoul'}
]

# 1. Create a new dictionary with id as key. Key puts the name and address of the same element in one list.
def merge(lst):
    answer = {}
    for i in lst:
        id = i['id']
        name = i['name']
        address = i['address']

        val = answer.get(id, {'name': [], 'address': []})
        val['name'].append(name)
        val['address'].append(address)
        answer[id] = val
    return answer

# 2. Convert dictionary made in (1) to list
def dict_to_list(lst):
    answer = [ {'id': key, **val} for key, value in lst.items()  ]
    return answer

merged_lst = merge(lst)
print(merged_lst)

result = dict_to_list(merged_lst)
print(result)


2022-09-22 18:50

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.