米琪卡哇伊
由于 dict 键是唯一的,我敢打赌您在源 dict 中有重复的描述。例如,假设您有以下数据集:bus_stops = [ {"Id": 1, "Description": "spam"}, {"Id": 2, "Description": "cheese"}, {"Id": 3, "Description": "spam"},]注意结果中只有最后一个“垃圾邮件”:>>> stop_map = {stop['Description']: stop for stop in bus_stops}{ 'cheese': {'Description': 'cheese', 'Id': 2}, 'spam': {'Description': 'spam', 'Id': 3}},}如果是这种情况,并且您想按描述对停靠点进行分组,则可以使用带有描述作为键和停靠点列表作为值的 dict - 该setdefault方法对于这种数据转换很方便:stop_map = {}for stop in bus_stops: stop_map.setdefault(stop["Description"], []).append(stop)结果:{ "cheese": [ { "Id": 2, "Description": "cheese" }, ], "spam": [ { "Id": 1, "Description": "spam" }, { "Id": 3, "Description": "spam" }, ],}