比较项目时字典重新排序

时间:2019-03-05 15:25:34

标签: python

我正在比较渡轮出发的字典LIVE_DEPARTURES_DATA,以确定它们是否具有相同的DEPARTURE TIMEDEPARTURE PORT。当我遍历它并进行相关检查时,我发现项目的顺序已更改。

live_departures_data = [{"COMPANY": "Alilauro", "DEPARTURE PORT": "Ischia", "ARRIVAL PORT": "Napoli Molo Beverello", "DEPARTURE DATE": "2019-03-03", "DEPARTURE TIME": "08:40", "ARRIVAL DATE": "2019-03-03", "ARRIVAL TIME": "09:30", "DURATION": "00:50:00", "FERRY TYPE": "Aliscafo", "STATUS": "Active"}, {"COMPANY": "Alilauro", "DEPARTURE PORT": "Procida", "ARRIVAL PORT": "Casamicciola", "DEPARTURE DATE": "2019-03-03", "DEPARTURE TIME": "08:40", "ARRIVAL DATE": "2019-03-03", "ARRIVAL TIME": "09:30", "DURATION": "00:50:00", "FERRY TYPE": "Aliscafo", "STATUS": "Active"}, {"COMPANY": "Alilauro", "DEPARTURE PORT": "Procida", "ARRIVAL PORT": "Napoli Molo Beverello", "DEPARTURE DATE": "2019-03-03", "DEPARTURE TIME": "08:40", "ARRIVAL DATE": "2019-03-03", "ARRIVAL TIME": "09:30", "DURATION": "00:50:00", "FERRY TYPE": "Aliscafo", "STATUS": "Active"}]

for i in range(len(live_departures_data)):
   for j in range(i + 1, len(live_departures_data)):
       if live_departures_data[i]["ARRIVAL PORT"] == live_departures_data[j]["ARRIVAL PORT"] and live_departures_data[i]["DEPARTURE TIME"] == live_departures_data[j]["DEPARTURE TIME"]:  
                live_departures_data[i].update({'STOPS': 'Via Procida'})
                live_departures_data[j].update({'STOPS': 'Via Procida'})

print(live_departures_data) 

以下是输出-为什么更改了订单?

[{'STATUS': 'Active', 'ARRIVAL DATE': '2019-03-03', 'DEPARTURE DATE': '2019-03-03', 'STOPS': 'Via Procida', 'DURATION': '00:50:00', 'ARRIVAL PORT': 'Napoli Molo Beverello', 'COMPANY': 'Alilauro', 'ARRIVAL TIME': '09:30', 'FERRY TYPE': 'Aliscafo', 'DEPARTURE TIME': '08:40', ...

更新:

我已经更新到Python 3.7并运行我的代码。我的初始订单被保留。

1 个答案:

答案 0 :(得分:4)

字典被定义为无序键值对。因此,您不能依赖他们的订购。如果您希望订单稳定,请使用collections.OrderedDict