Why are dictionary values being overriden at the end of this loop?

前端 未结 1 706
眼角桃花
眼角桃花 2021-01-28 12:45

I have a dictionary of public transportation stops called stops. I want to duplicate the ones that are transfers (have more than one line) so that there is a duplicate stop in s

相关标签:
1条回答
  • 2021-01-28 12:59

    Then duplicates[duplicate_stop] and stops[item] both name the same object - and mutating the object, well, changes the object. Objects are not automatically copied/cloned/duplicated on an assignment or when used as function arguments.

    The problematic line is most likely

    duplicates[new_map_id] = stops[item] # duplicate the stop
    

    .. and the comment is wrong because there is no duplication that occurs.


    The question Understanding dict.copy() - shallow or deep? may be useful; at the very least it shows how to make a real copy.

    0 讨论(0)
提交回复
热议问题