AkshaiShah
AkshaiShah

Reputation: 5939

Python - How to search a dictionary for a specific string?

If I have a dictionary defined as users = {}, and lets say I have some data in that dictionary, how could I search through the dictionary, and do nothing if my search string matches a string in my dictionary.

for socket.user in MyServer.users:
    if ((MyServer.users.has_key(socket.user)) == false):
        MyServer.users[user].send(socket.message)

So here is searches the users dictionary, and finds that it is present, so it should do nothing. I know my code is wrong, but what could I change on the second line?

Upvotes: 1

Views: 23769

Answers (4)

atomAltera
atomAltera

Reputation: 1791

users = {"A": 0, "B": 1, "C": 2}

key = "B"
value = "2"

if key in users: print("users contains key", key)
if value in users.values(): print("users contains value", value)

Upvotes: 5

Daniel Pryden
Daniel Pryden

Reputation: 60997

Am I missing something, or is this what you are looking for:

if socket.user in MyServer.users:
    # Send a message if it's a valid user
    MyServer.users[user].send(socket.message)
else:
    # Do nothing if it isn't
    pass

Upvotes: 0

log0
log0

Reputation: 10947

How could I search through the dictionary, and do nothing if my search string matches a string in my dictionary.

if socket.user in MyServer.users: # search if key is in dictionary
   pass # do nothing

Upvotes: 3

PenguinCoder
PenguinCoder

Reputation: 4367

In python, you can use the pass keyword to essentially 'do nothing'.

for socket.user in MyServer.users:
    if MyServer.users.has_key(socket.user) == False:
        pass

However the more proper way would be to write your code in a manner that does what you WANT it to do; not doing what you don't NEED it to do.

for socket.user in MyServer.users:
    if MyServer.users.has_key(socket.user) == True:
        MyServer.users[user].send(socket.message)

Upvotes: 1

Related Questions