Diolor
Diolor

Reputation: 13450

Join two Python dictionaries based on same value but different key name (like SQL's JOIN)

With same keys in dictionaries, I have found this answer

However I want to merge the previous example's dictionaries as if I had these two:

list_a = {'data' : [{'user__name': u'Joe', 'user__id': 1},
                    {'user__name': u'Bob', 'user__id': 3}]}
list_b = {'data' : [{'hours_worked': 25, 'user_num': 3},
                    {'hours_worked': 40, 'user_num': 1}]}

I tried:

for (k,v) in list_a['data']:
    list_a['data'][k]['user_num'] = list_a['data'][k].pop('user__id')

But I got: ValueError: too many values to unpack

Update:

I want my final result look like:

list_c = {'data' : [{'user__name': u'Joe', 'user_num': 1, 'hours_worked': 40},
                    {'user__name': u'Bob', 'user_num': 3, 'hours_worked': 25 }]}

Upvotes: 1

Views: 1819

Answers (3)

roman
roman

Reputation: 117510

>>> res = {d["user_num"]: d for d in list_b["data"]}
>>> for a in list_a["data"]:
...     res[a["user__id"]]["user__name"] = a["user__name"]
>>> list_c = {"data" : res.values()}

However, it will raise KeyError if there's no user in list_b for user in list_a

Upvotes: 1

sihrc
sihrc

Reputation: 2848

Something like this?

list_a = [{'user__name': u'Joe', 'user__id': 1},
          {'user__name': u'Bob', 'user__id': 3}]
list_b = [{'hours_worked': 25, 'user_num': 3},
          {'hours_worked': 40, 'user_num': 1}]

worker_directory = dict()
for _dict in list_a:
    user_dict = dict()
    user_dict['user__id'] = _dict['user__id']
    worker_directory[_dict['user__name']] = user_dict

for _dict in list_b:
    for worker,worker_dict in worker_directory.items():
        if worker_dict['user__id'] == _dict['user_num']:
            worker_dict['hours_worked'] = _dict['hours_worked']


print worker_directory

Worker_directory is a dictionary of workers with values - dictionaries that contain user id and hours worked.

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1123590

In that case you'd have to use a dictionary to map ids to dictionaries first:

result = {d['user__id': d for d in list_a}
for d in list_b:
    if d['user_num'] in result:
        result[d['user_num']].update(d)

Upvotes: 2

Related Questions