简体   繁体   中英

Checking if a list is already in the dictionary in python

I am trying to check if a list s already in a dictionary in python. My code is supposed to generate 2 random numbers(r1 and r2) and append them to a list in the dictionary if those same 2 numbers aren't already in there. Here is the code:

main_dict = {0:[], 1:[], 2:[], 3:[], 4:[]}
for x in range(0,5):
    r1 = randint(1,5)
    r2 = randint(1,5)
    temp = [r1,r2]
    if temp not in main_dict:
        main_dict[x].append(r1)
        main_dict[x].append(r2)

So basically main_dict should look something like this: {0:[2,3],1:[4,1],2:[3,3],3:[3,2],4:[5,1]}, and the code above should take care that no combination is repeated.

The error is "TypeError:unhashable type: 'list'", and i guess it is because i can't put a list next to an if, but i have no idea what else to put, i have tried everything that came to my mind.

Thanks in advance :)

the problem you are getting is because you are looking in a dictionary if the list exists. With that, you are comparing your list with the keys of the dictionary. What you want to do is:

if temp not in manin_dict.values():

if temp not in main_dict: if temp not in main_dict.values():

A list can't be hashed because it can be changed. What you want can be done efficiently using tuples instead of lists and a set to avoid duplicates. There may be some issues to work around if you intended to change the lists though.

main_dict = dict((i,[]) for i range(0,5))
main_set = set()
for x in range(0,5):
    r1 = randint(1,5)
    r2 = randint(1,5)
    temp = (r1,r2) # This is the same as tuple([r1,r2])
    if temp not in main_set:
        main_dict[x] = temp
        main_set.add(temp)

Note you can avoid the dictionary and just add to the set if you just want the set of tuples. The reason for using a set is that checking if an element is in the set is O(1) while checking if an element is in the list of dictionary values is O(N). Not something you'd notice with only 5 values, but definitely so if you had significantly more.

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