Python - Dictionary in class not functioning as expected
<p>I have a very basic class <code>Library</code>, and I initialize it with a passed in dictionary (key book name (string), value book shelf location (int)) with values already entered into it. The code looks like this:</p>

<pre><code>class Library(object):
    def __init__(self, book_table):
        self.book_table = book_table

    def get_location(self, book_name):
        if book_name in self.book_table: # ERROR RIGHT HERE
            return self.book_table[book_name]
        else:
            return "Book Not Found"

libraries = []
libraries.append(Library({"Book1":2, "Book2":9}))
print Library(libraries[0]).get_location("Book1")
</code></pre>

<p>For some reason, I am unable to access data from the dictionary from the get_location method, but I am able to access the dictionary data in the initialize method (and I previously tested the represent method and it worked in there too). This is the error I get:</p>

<pre><code>Traceback (most recent call last):
  File "C:/Users/Owner/Documents/Programming/PyCharm/Book_Locator/Book_Locator.py", line 13, in &lt;module&gt;
    print Library(libraries[0]).get_location("Book1")
  File "C:/Users/Owner/Documents/Programming/PyCharm/Book_Locator/Book_Locator.py", line 6, in get_location
    book_name in self.book_table:
TypeError: argument of type 'Library' is not iterable
</code></pre>

<p>I expected it to print out Book1's location, which is a 2.</p>

<p>You are creating a <em>new</em> <code>Library</code> instance that you pass your existing instance into:</p>

<pre><code>print Library(libraries[0]).get_location("Book1")
#     ^^^^^^^ ^^^^^^^^^^^^
#        |        \----------- an existing instance of Library
#  A new instance of Library
</code></pre>

<p>This gives you a <code>Library()</code> instance where <code>book_table</code> is <em>another</em> <code>Library()</code> instance, not a dictionary!</p>

<p>You'd want to call <code>get_location()</code> <em>directly</em> on <code>libraries[0]</code>:</p>

<pre><code>print libraries[0].get_location("Book1")
</code></pre>

<p>You could also just store <em>just</em> the <code>book_table</code> dictionary in the list:</p>

<pre><code>libraries = [{"Book1": 2, "Book2": 9}]
print Library(libraries[0]).get_location("Book1")
</code></pre>

<p>but this would only be needed if you could not store <code>Library</code> instances in the list directly for whatever reason.</p>

python dictionary