1

在字典中使用相同的键,我找到了这个答案

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

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

3 回答 3

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_b 中没有用户对于 list_a 中的用户,它将引发 KeyError

于 2013-07-30T14:36:49.203 回答
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)
于 2013-07-30T14:22:19.437 回答
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 和工作时间的字典。

于 2013-07-30T14:26:35.127 回答