简体   繁体   中英

Checking if Dict Value exists

I tried searching for an answer but did not find anything that helps. So I have to ask.

I have a password collector which right now runs every time I run the script. The value is then stored in memory to use it for that session.

Even if I close that script as long as maya is still open, I can access the password.

What I need is a way to see if the value is already in the memory or not. When I use

print argdict['password']

I can see that the dict is in my memory. I tried to get something like

if argdict['password'] in locals():
    print 'its alive'

but that doesn't return anything, what would be the correct way to check if a dict key or value exists or not.

用这个:
if 'password' in argdict:

To test if "password" is among the values of your dictionary.

 "password" in d.itervalues()

To test if "password" is among the keys of your dictionary.

 "password" in d.keys()

你可以使用它做in

if 'password' in argdict:

Something I think may be more elegant is:

if argsdict.get('password', False):
    # do whatever

It will try to see if argsdict has a 'password' key/value pair, but if not, it will resort to the default value, which I provided as False. Thus, the conditional becomes if False when there is not 'password' key, so the conditional block will not run.

However, this also will not execute if you have an object that is considered False as the value of 'password'. Various values that are evaluated as False (try bool(some_object) to see whether it is evaluated as True or False): 0, None, '', {}, [] , etc. Most empty containers are False .

Because of this, this is probably your best bet:

if 'password' in argsdict:

The correct way to check if the dict exists is to simply use the name:

>>> d = dict()
>>> 'd' in locals()
True

And to see if it's a dict:

>>> isinstance(d, dict)
True

To check for the key:

>>> d['password'] = 'foo'
>>> 'password' in d
True

To check that a value exists (and is non-empty):

>>> if d.get('password'): print True
...
True

To check if the value is a particular value:

>>> d.get('password') == 'foo'
True

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