简体   繁体   中英

How to create a list containing N Lists each containing N distinct dictionaries using comprehension syntax?

    oneCounts = [[{'l':0,'r':0,'t':0,'b':0}] * N for i in range(0,N)]     
    oneCounts[0][1]['t'] = 3

In the above code setting key value on a specific dictionary causes all dictionaries in the same list to get their t key values get set to the same value. This is unexpected to me. What am I missing?

Change the first line to

oneCounts = [[{'l':0,'r':0,'t':0,'b':0} for _ in range(N)] for i in range(0, N)] 
# oneCounts = [[{'l':0,'r':0,'t':0,'b':0} for _ in range(N)] for _ in range(N)] 

in order to create independent dictionaries.

[x] * n creates a list of n references to the same object x . You should only use that syntax when x is of an immutable type, eg int .

The reason behind the unexpected result is you are calling the constructor just once and then using the same object N times. So, in effect, you are appending the same object N times to oneCounts because the lists containing the dictionaries have the same reference.

Try out the following:

oneCounts = []
for i in range(N):
    oneCounts.append([{'l':0,'r':0,'t':0,'b':0} for j in range(N)])

Here, oneCounts is a list containing N Lists and each list contains N separate dictionaries.

edit : I just noticed the answer given by user 'schwobaseggl'. It does the same thing as my code, but with less typing. I personally like that answer better.

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