合并两个不同索引的词典

时间:2017-07-20 14:31:55

标签: python json dictionary

我想合并这本词典:

b = {data:[{station_id: 7000,
 name: "Ft. York / Capreol Crt."
 },
 {station_id: 7001,
  name: "Lower Jarvis St / The Esplanade"}
 ]}

和这一个:

c = {data:[{station_id: 7000,
 num_bikes_available: 18,
 },
 {station_id: 7001,
  num_bikes_available: 4,
  },
 {station_id: 7002,
  num_bikes_available: 10}      
]}

并获得一个这样的词典:

d = {data:[{station_id: 7000,
     name: "Ft. York / Capreol Crt.",
     num_bikes_available: 18
      },
    {station_id: 7001,
     name: "Lower Jarvis St / The Esplanade",                         
     num_bikes_available: 4},
    {station_id: 7002,
     num_bikes_available: 10} 
    ]}

我该怎么做?请记住,在c中我们有一个station_id = 7002,而在b中我们没有。

4 个答案:

答案 0 :(得分:0)

我希望这有帮助!

dct = {'a':'b','b':'c'}
dct1 = {'a':'b','d':'c'}
ndict = dict(dct.items() + dct1.items())
print ndict

控制台输出:

{'a': 'b', 'b': 'c', 'd': 'c'}

答案 1 :(得分:0)

首先,您可以从b创建一个临时字典,以便于查找。

In [812]: temp = { x['station_id'] : x for x in b['data'] }

接下来,您迭代c并更新b中存在的词典:

In [813]: d = c.copy()

In [814]: for _dict in d['data']:
     ...:     if _dict['station_id'] in temp:
     ...:         _dict.update(temp[_dict['station_id']])
     ...:         

In [815]: d
Out[815]: 
{'data': [{'name': 'Ft. York / Capreol Crt.',
           'num_bikes_available': 18,
           'station_id': 7000},
          {'name': 'Lower Jarvis St / The Esplanade',
           'num_bikes_available': 4,
           'station_id': 7001},
          {'num_bikes_available': 10, 
           'station_id': 7002}]}

答案 2 :(得分:0)

res = {}
for station_dict in b['data']:
    station_id = station_dict.pop('station_id')
    res.setdefault(station_id, {}).update(station_dict)
for station_dict in c['data']:
    station_id = station_dict.pop('station_id')
    res.setdefault(station_id, {}).update(station_dict)

答案 3 :(得分:0)

我们可以将每个“数据”的dicts列表解压缩为dicts的dict,以便更容易合并内部dicts的内容,然后我们可以从合并的数据中创建原始格式的新dicts列表。在合并期间,如果.setdefault的词典在c中不存在,我们会使用b创建一个空词典。新列表按station_id排序。

from pprint import pprint

b = {'data': [{'name': 'Ft. York / Capreol Crt.', 'station_id': 7000},
          {'name': 'Lower Jarvis St / The Esplanade', 'station_id': 7001}]}

c = {'data': [{'num_bikes_available': 18, 'station_id': 7000},
          {'num_bikes_available': 4, 'station_id': 7001},
          {'num_bikes_available': 10, 'station_id': 7002}]}

def unpack(old):
    return {d["station_id"]: d.copy() for d in old['data']}

temp = unpack(b)
for k, v in unpack(c).items():
    temp.setdefault(k, {}).update(v)

# repack
d = {"data": [temp[k] for k in sorted(temp.keys())]}
pprint(d)

<强>输出

{'data': [{'name': 'Ft. York / Capreol Crt.',
           'num_bikes_available': 18,
           'station_id': 7000},
          {'name': 'Lower Jarvis St / The Esplanade',
           'num_bikes_available': 4,
           'station_id': 7001},
          {'num_bikes_available': 10, 'station_id': 7002}]}

可以轻松修改此代码以处理2个以上的输入对象。请注意,合并过程不会更改原始对象。