加入两个基于相同值但不同键名的Python词典(如SQL的JOIN)

时间:2013-07-30 14:15:24

标签: python dictionary key

在词典中使用相同的键,我找到了this answer

但是我想合并上一个例子的字典,好像我有这两个:

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}]}

我试过了:

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

但我得到了:ValueError: too many values to unpack

更新

我希望我的最终结果如下:

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

3 个答案:

答案 0 :(得分:1)

在这种情况下,您必须先使用字典将ID映射到字典:

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)

答案 1 :(得分:1)

>>> 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()}

但是,如果list_a

中的用户没有list_b中的用户,则会引发KeyError

答案 2 :(得分:0)

这样的东西?

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是一个包含值的工作人员的字典 - 包含用户ID和工作小时数的字典。