简体   繁体   中英

How do i make a shallow copy of a list containing a dictionary?

For a game I made in python pygame, I have a tutorial class with a list of stages, each containing a dictionary in each stage that holds a title and keys needed to be pressed. To ensure the player hit each key, I made a copy of the list, thinking that would make a copy of the contents as well. However, whenever I reduced the keys pressed in the dictionary, it would work for the first time as the ids of keys needed to be pressed were removed from the dictionary in each stage. However, I soon realized that when I restarted the tutorial, the copy of the hardcoded list wasn't a true copy, since the dictionaries in the copied list were changed both in the copied list and in the uncopied list.

Here is the problem:

list_test = [{'dictionary': 1, 'asdf': 2}, {'dictionary':2, 'asdf':3}]
list_copy = list_test[:]
#this happens to only ensure that appended or popped items don't change the initial list.
# What happens when i edit a dictionary
list_copy[0]['dictionary'] = 123
assert not list_copy[0]['dictionary'] == list_test[0]['dictionary']

The last test is false, since somehow editing the lower level in a copied list edits both lists.

All advice is welcome!

As long as the list only contains dictionaries this should work

list_copy = [dict(i) for i in list_test]

or

list_copy = [i.copy() for i in list_test]

that way you will create a list of copies of the dictionaries, rather than references to the original dictionaries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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