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>@nk001,<br>
I think this is a little more like what you are trying for:</p>

<pre><code>class Test(object): 
    def __init__(self, x=0):
        self.x = x               # &lt;-- indent the __init__ statements

    users = {                    # &lt;-- users = {
        'John': 1,               #         KEY: VALUE,
        'Jim':  2,               #         KEY: VALUE,
        'Bob':  3                #         KEY: VALUE,
    }                            #     }

    def find(self, x):             # &lt;-- The user passes the "x" argument

        for i in self.users:       # &lt;-- Now it goes through the dictionary 
            if x == i:             # &lt;-- If ARGV('x') == KEY
                return 'worked'    # &lt;-- Then RETURN 'worked'
            else:
                pass


beta = Test()
print(beta.find("Jim"), beta.users["Jim"])
</code></pre>

<p>There's a couple different ways to get the 'worked' msg and the corresponding Value printed, this is just an example to demonstrate accessing the dict[KEY] to get the VALUE.  </p>

<p>Also, I'm just assuming you meant an if/else block, and not a for/else? Indentation is critical w/Python. Also, your original script was returning None because there was no explicit <code>return</code> in your for loop - hence, when the function is called in the printing statement <code>print(beta.find('Jim'))</code> when the function finishes it returns nothing ("None"). Hope that helps!</p>

python