Leemosh
Leemosh

Reputation: 905

merge dictionary and list of dictionaries in a specific way

Not working too much with dictionaries and thinking about it for too long. I'm looking for merging dictionaries in a way I'm describing a little lower. Dictionary might be a bit bigger.

Thanks!

dict1:

{'0': '5251', '1': '5259'}

list:

[{'id': 5259, 'name': 'chair'}, {'id': 5251, 'name': 'table'}]

Result:

{'0': {'id': 5251, 'name': 'table'}, '1': {'id': 5259, 'name': 'chair'}}

Upvotes: 0

Views: 63

Answers (4)

Swaroop
Swaroop

Reputation: 1289

d = {'0': '5251', '1': '5259'}
l = [{'id': 5259, 'name': 'chair'}, {'id': 5251, 'name': 'table'}]

# Lets prepare an intermediate dict for faster computation on large data
d1 = {str(x['id']): x for x in l}

merged_dict = {x: d1[y] for x, y in d.items()}
print(merged_dict)

Upvotes: 1

jorf.brunning
jorf.brunning

Reputation: 472

Construct a dictionary with reversed keys and values from your original:

d = {'0': '5251', '1': '5259'}
rev_dict = {v: k for k, v in d.items()}

Now you can use the id from each item of your list as an index into your dict

l = [{'id': 5259, 'name': 'chair'}, {'id': 5251, 'name': 'table'}]
merged_data = {rev_dict[str(x['id'])]: x for x in l}

# {'1': {'id': 5259, 'name': 'chair'}, '0': {'id': 5251, 'name': 'table'}}

Upvotes: 1

StardustGogeta
StardustGogeta

Reputation: 3406

This should work:

dict1 = {'0': '5251', '1': '5259'}
ls = [{'id': 5259, 'name': 'chair'}, {'id': 5251, 'name': 'table'}]

idToEntry = dict([x['id'], x] for x in ls)
dict2 = dict([k, idToEntry[int(v)]] for k, v in dict1.items())
print(dict2)

The output:

{'0': {'id': 5251, 'name': 'table'}, '1': {'id': 5259, 'name': 'chair'}}

Upvotes: 1

Philip Ciunkiewicz
Philip Ciunkiewicz

Reputation: 2791

This solution will be somewhat slow for larger lists, but it is very simple:

result = {}
for key, val in dict1.items():
    for dict2 in list1:
        if dict2['id'] == val:
            result['key'] = dict2

Upvotes: 1

Related Questions