How to loop through keys in a dict to find the corresponding value?
<p>When a user enters a name (e.g. "Jim") as an argument for an instance of my "Test" class, the <code>def find</code> function is called and for-loops through all the names in the dict matching "Jim".  If <code>def find</code> finds the key word "Jim" in the dict, then it should print out the corresponding value.  But when I run the code it just says "None". What do I need to change so that invoking <code>def find</code> results in the print statement 'worked'??</p>

<pre><code>class Test(object): 
    def __init__(self, x=0): # error in (def find)?
        self.x = x

    c = None                 # error while looping in the for loop?
    users = {
        'John': 1,
        'Jim':  2,
        'Bob':  3
    }

    def find(self, x):       # The user is supposed to type in the name "x"

        for self.c in self.users:         # it goes through the dictionary 
            if x == self.users[self.c]:   # If x is equal to key it prints worked
                print('worked')
            else:
                pass


beta = Test()
print(beta.find('Jim'))
</code></pre>

<p>I write a worked code:</p>

<pre><code>class Test(object):
    users = {
        'John': 1,
        'Jim': 2,
        'Bob': 3
    }

    def __init__(self, x=0): # So I don't get an error in (def find)
        self.x = x

    def find(self, x):  # The user is suppose to type in the name "x"
        for name in Test.users.keys():   # it goes through the dictionary
            if x == name: # If x is equal to key it prints worked
                print('worked', self.users[name])
            else:
                pass


beta = Test()
beta.find('Jim')
</code></pre>

<ol>
<li>You don not need the <code>self.c</code>.</li>
<li>The <code>users</code> is a class variable, you need to visit it by <code>Test.users</code>.</li>
<li>Your names is stored as the keys of the dict. So you need to get them by <code>Test.users.keys()</code></li>
<li>The statement <code>print(beta.find('Jim'))</code> will print the return value of the <code>find</code>. But you don't return a value manually, you will get a <code>None</code> in your output.</li>
</ol>

python