简体   繁体   中英

Check if a Key from dictionary is same as a dictionaries's key in list

I have a list

banned = []

and a tuple

address = ('127.0.0.1', 37670)

I'm accessing the first value ( ip ) as address[0] . So I inserted this ip to the new dictionary banned_user with a zero value for count.

banned_user = {adress[0]:0}

So I would like to know how to append banned_user to banned list if it not already contains. Like I'm doing like this

banned.append(banned_user.copy())

but I don't know how to check if ip from banned_user is in banned . If not I want to append it there with that zero value and if there is I want that zero to be +1 (plus). Can somebody please help me?

You could use a dictionary for banned , then lookup would be very fast. Since you're only using one part of the tuple (the string part) you could use that elements as the keys.

banned = {}
address_tuple = ('127.0.0.1', 37670)

user_address, user_port = address_tuple

if user_address in banned:
    banned[user_address] += 1
else:
    banned[user_address] = 0

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