0

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'}}
Leemosh
  • 883
  • 6
  • 19
  • Maybe look here https://stackoverflow.com/questions/38987/how-do-i-merge-two-dictionaries-in-a-single-expression-taking-union-of-dictiona – Petr Synek Jul 16 '21 at 15:47

4 Answers4

1

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
Philip Ciunkiewicz
  • 2,652
  • 3
  • 12
  • 24
1

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'}}
StardustGogeta
  • 3,331
  • 2
  • 18
  • 32
1

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'}}
jorf.brunning
  • 452
  • 4
  • 9
1
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)
Swaroop
  • 1,219
  • 3
  • 16
  • 32