Skip to main content
 首页 » 编程设计

python之字典 : how to compare values and merge if values are the same

2024年11月01日9zfyouxi

如果我有两个字典:

 [{u'id': 217110, 
  u'label': u'Business A', 
  u'score': 0}, 
 {u'id': 217111, 
  u'label': u'Business B', 
  u'score': 0}, 
 {u'id': 217112, 
  u'label': u'Business Yada Yada', 
  u'score': 0'}] 

和

[{u'City': u'Damariscotta', 
  u'EntityType': u'Maine Public', 
  u'EntityTypeCode': u'1', 
  u'Status1': u'Open', 
  u'ID': u'0188', 
  u'Name1': u'A Company 000', 
  u'UpdateTimeUnix': 1363756455}, 
{u'City': u'Santa Barbra', 
  u'EntityType': u'California Public', 
  u'EntityTypeCode': u'1', 
  u'Status1': u'Delayed', 
  u'ID': u'1001', 
  u'Name1': u'Business A', 
  u'UpdateTimeUnix': 1363758764}, 
{u'City': u'Boise', 
  u'EntityType': u'Idaho Public', 
  u'EntityTypeCode': u'1', 
  u'Status1': u'Closed', 
  u'ID': u'1012', 
  u'Name1': u'Business Yada Yada', 
  u'UpdateTimeUnix': 1363759375}, 
{u'City': u'Elkhart', 
  u'EntityType': u'Indiana Public', 
  u'EntityTypeCode': u'1', 
  u'Status1': u'Open', 
  u'ID': u'1016', 
  u'Name1': u'Business B', 
  u'UpdateTimeUnix': 1363826341}] 

简而言之,什么是获得它的有效方法?:

 [{u'id': 217110, 
  u'label': u'Business A', 
  u'score': 0, 
  u'Status1': u'Delayed'}, 
 {u'id': 217111, 
  u'label': u'Business B', 
  u'score': 0, 
  u'Status1': u'Open'}, 
 {u'id': 217112, 
  u'label': u'Business Yada Yada', 
  u'score': 0', 
  u'Status1': u'Open'}] 

请您参考如下方法:

使用 operator.itemgetter:

from operator import itemgetter 
key1 = itemgetter("Name1") 
key2 = itemgetter("label") 
key3 = itemgetter("Status1") 
for record in b: # this is the longer list of dicts 
    k = key1(record) 
    for record2 in a: #this is the shorter one 
        if key2(record2) == k: 
            record2['Status1'] = key3(record) 
 
print a 

输出:

[{u'score': 0, 'Status1': u'Delayed', u'id': 217110, u'label': u'Business A'}, {u'score': 0, 'Status1': u'Open', u'id': 217111, u'label': u'Business B'}, {u'score': 0, 'Status1': u'Closed', u'id': 217112, u'label': u'Business Yada Yada'}]