1

I've got a Python dictionary, as follows:

users = {'user': {'pw': 'password'}}

How do I check if the value exist in the dictionary?

I would receive a false in the following if statement:

if 'password' in users:
        return 'true'
else:
        return 'false'
lord63. j
  • 4,500
  • 2
  • 22
  • 30
luishengjie
  • 187
  • 6
  • 15
  • 1
    You should organize your data in such a way that the operations you want to perform are cheap, and finding out whether a dictionary contains a value is already expensive, let alone a nested value. Also, there is pretty much never a reason to check whether a password is in use. It just leaks information and makes it easy to break into your system. – user2357112 Dec 06 '15 at 04:08
  • 1
    @user2357112 My intuition is that the OP won't understand what you have just said. – nbro Dec 06 '15 at 04:09
  • @nbro: Mine too, but exposure to the information may be useful for future understanding, even if he doesn't understand it now. – user2357112 Dec 06 '15 at 04:13

2 Answers2

1

You have a dictionary within a dictionary, so to check if any user (top level) has password (key 'pw') set to 'password', you can use:

return 'password' in (user['pw'] for user in users.itervalues())

Also note that the boolean values in Python are True and False. If you wanted to return strings 'true' and 'false', you can do:

return 'true' if 'password' in (user['pw'] for user in users.itervalues()) else 'false'
Szymon
  • 42,577
  • 16
  • 96
  • 114
-1

You would do

if users['user']['pw'] == 'password':
    return 'true'
else:
    return 'false'
dursk
  • 4,435
  • 2
  • 19
  • 30