简体   繁体   English

在Python中合并两个字典?

[英]Merging two dictionaries in Python?

I want to merge this dictionary: 我想合并这本字典:

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

and this one : 还有这个 :

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

and get one dictionary like this: 并得到一本这样的字典:

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

How can I do that? 我怎样才能做到这一点?

For Py>3.5: 对于Py> 3.5:

It's easy. 这很容易。 Just enter: 只需输入:

d = {**b, **c}

The key to this problem is picking the right data structure. 解决此问题的关键是选择正确的数据结构。 Instead of b['data'] being a list , it should be a dict indexed by the merge key. 而不是b['data']list ,它应该是由合并键索引的dict The following code first converts b and c into dict s indexed by station_id , then merges those dictionaries. 以下代码首先将bc转换为由station_id索引的dict ,然后合并这些字典。

Try this: 尝试这个:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM