使用 for 循环合并两个具有相同键的字典

Merge two dictionaries with an identical key using foor loop

我有这两个词典,我想在dict2中添加数据dict1。我怎样才能用 python 做到这一点?

dict1 = {
    213688169:
        {'stationCode': '6003',
         'station_id': 213688169,
         'num_bikes_available': 10,
         'numBikesAvailable': 10,
         'num_bikes_available_types': [{'mechanical': 10}, {'ebike': 0}],
         'num_docks_available': 10,
         'numDocksAvailable': 10,
         'is_installed': 1,
         'is_returning': 1,
         'is_renting': 1,
         'last_reported': 1619207955}
}

dict2 = {
    213688169:
        {'station_id': 213688169,
         'name': 'Benjamin Godard - Victor Hugo',
         'lat': 48.865983,
         'lon': 2.275725,
         'capacity': 35,
         'stationCode': '16107'}
}

我试过了,但是它太长太复杂了:

donnees=[]
for i in stations:
    for j in velib_description :
         if i['station_id'] == j['station_id']:
                List={}
                List['name'] = i['name']
                List['lat'] = i['lat']
                List['lon'] = i['lon']
                List['capacity'] = i['capacity']
                List['num_bikes_available'] = j['num_bikes_available']
                List['num_bikes_available_types'] = j['num_bikes_available_types']
                List['last_reported'] = j['last_reported']
                donnees.append(List)

我想加入dict_2 = {num_bikes_available', 'num_bikes_available_types', last_reported': 1619207955 }

谢谢

您可以使用带有 dictionary merge trick:

的字典理解
dict3 = {k: {**v, **dict2[k]} for k, v in dict1.items()}

或 Python 3.9 及更高版本:

dict3 = {k: v | dict2[k] for k, v in dict1.items()}

也许你想要dict.update

dict1 = {
    213688169: {
        "stationCode": "6003",
        "station_id": 213688169,
        "num_bikes_available": 10,
        "numBikesAvailable": 10,
        "num_bikes_available_types": [{"mechanical": 10}, {"ebike": 0}],
        "num_docks_available": 10,
        "numDocksAvailable": 10,
        "is_installed": 1,
        "is_returning": 1,
        "is_renting": 1,
        "last_reported": 1619207955,
    }
}

dict2 = {
    213688169: {
        "station_id": 213688169,
        "name": "Benjamin Godard - Victor Hugo",
        "lat": 48.865983,
        "lon": 2.275725,
        "capacity": 35,
        "stationCode": "16107",
    }
}

dict1_item = dict1[213688169]
dict2[213688169].update({k: v for k, v in dict1_item.items() if k not in dict2})

dict2

这会打印

{213688169: {'station_id': 213688169,
  'name': 'Benjamin Godard - Victor Hugo',
  'lat': 48.865983,
  'lon': 2.275725,
  'capacity': 35,
  'stationCode': '6003',
  'num_bikes_available': 10,
  'numBikesAvailable': 10,
  'num_bikes_available_types': [{'mechanical': 10}, {'ebike': 0}],
  'num_docks_available': 10,
  'numDocksAvailable': 10,
  'is_installed': 1,
  'is_returning': 1,
  'is_renting': 1,
  'last_reported': 1619207955}}

我们正在使用理解从第一个词典中获取第二个词典中不存在的所有 key/values,然后更新第二个词典。我们必须对 213688169 键做一些修改,因为你的字典是嵌套的。