合并Python中的两个词典?

时间:2017-07-20 01:26:19

标签: python 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,
      }
    ]}

并获得一个这样的词典:

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

我该怎么做?

2 个答案:

答案 0 :(得分:2)

对于Py> 3.5:

这很容易。只需输入:

d = {**b, **c}

答案 1 :(得分:1)

这个问题的关键是选择正确的数据结构。而b['data']不是list,而应该是合并键索引的dict。以下代码首先将bc转换为dict索引的station_id,然后合并这些词典。

试试这个:

from pprint import pprint

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

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

# First, convert B and C to a more useful format:

b1 = {item['station_id']: item for item in b['data']}
c1 = {item['station_id']: item for item in c['data']}

# Now construct D by merging the individual values
d = {'data': []}
for station_id, b_item in sorted(b1.items()):
    z = b_item.copy()
    z.update(c1.get(station_id, {}))
    d['data'].append(z)

pprint(d)