繁体   English   中英

Python:具有相同值(可变类型)的多个键。 更改这些值之一也会更新其他值。 如何避免这种情况?

[英]Python: Multiple keys with same values (mutable type). Changing one of these values updates the other values too. How do I avoid this?

incident_data_dict = {}
for cause in causes_dict:
    if driver in incident_data_dict or vehicle in incident_data_dict:
        incident_data_dict[driver][cause] += causes_dict[cause]
        incident_data_dict[vehicle][cause] += causes_dict[cause]
    else:
        incident_data_dict.update({driver: causes_dict})
        incident_data_dict.update({vehicle: causes_dict})

event_data_dict = {u'Vehicle_1':{'Over Speeding':0,'Over Acceleration':2,'Hard Braking':0},u'Driver_1':{'Over Speeding':0,'Over Acceleration':2 ,'Hard Braking':0}}

参考图

u'Vehicle_1' (103072304) = {dict} {'超速':0,'超加速':2,2,'硬制动':0}'硬制动' (107104320) = {int} 0'超加速' ( 107104360) = {int} 2个“超速行驶” (107104680) = {int} 0

u'Driver_1' (103088424) = {dict} {'超速':0,'超加速':2,2,'硬制动':0}'硬制动' (107104320) = {int} 0'超加速' ( 107104360) = {int} 2个“超速行驶” (107104680) = {int} 0

像这样更新event_data_dict [driver]:event_data_dict [driver] [cause] + = Causes_dict [cause]也更新了event_data_dict [vehicle]中的“ cause”键,这是因为所有“ cause”键都有相同的引用。 这会使这些键增加两次,而不是一次。 我该如何克服呢?

您可以对字典进行深度复制

import copy
incident_data_dict2=copy.deepcopy(incident_data_dict)
#both dictionaries are independent

暂无
暂无

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

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