English 中文(简体)
How do I use __getitem__ and __iter__ and return values from a dictionary?
原标题:

I have an object with a dictionary that I want to access via __getitem__ as well as iterate over (values only, keys don t matter) but am not sure how to do it.

For example:

Python 2.5.2 (r252:60911, Jul 22 2009, 15:33:10) 
>>> class Library(object):
...   def __init__(self):
...     self.books = {  title  : object,  title2  : object,  title3  : object, }
...   def __getitem__(self, i):
...     return self.books[i]
... 
>>> library = Library()
>>> library[ title ]
<type  object >
>>> for book in library:
...   print book
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in __getitem__
KeyError: 0
>>> 

How do I tell it to simply return the object for each item in the dictionary (the key doesn t matter) ?

最佳回答
def __iter__(self): return self.books.itervalues()
问题回答

Add this method to Library:

def __iter__(self):
  return self.books.itervalues()

This delegates iteration to the dict, which has an easy method to iterate values. Read about the iterator protocol, which consists of __iter__ (on all iterables) and next(__next__ in 3.x) (only on iterators) methods.

You can return an iterator from your inner data:

class Library (object):
  ...
  def __iter__(self):
    return self.books.itervalues()

itervalues() returns an iterator to the values of the dictionary.

If you want more control, you can make __iter__ a generator function

class Library (object):
  ...
  def __iter__(self):
    for title in self.books:
      yield self.books[title]

in this case, this generator yields the exact same as the iterator in the first example.

>>> class Library(object):
...     def __init__(self):                                                     
...             self.books = {  title  : object,  title2  : object,  title3  : object, }
...     def __getitem__(self, i):
...             return self.books[i]
...     def __iter__(self):
...             return self.books.itervalues()
... 
>>> library = Library()
>>> library[ title ]
<type  object >
>>> for book in library:
...     print book
... 
<type  object >
<type  object >
<type  object >

__getitem__(self,key), where key is a integer, as your self.books is a dictionary and you can not do self.books[integer]

e.g:

>>>d = { a : sdsdsd , b : sfsdsd }
>>d[0]

d[0]
Traceback (most recent call last):
  File "<console>", line 1, in <module>
KeyError: 0

the iteration protocol goes like this:

The iterator protocol consists of two methods. The __iter__() method, which must return the iterator object and the next() method, which returns the next element from a sequence. previously when __iter__ method was not defined, it fell back to __getitem__ by successively calling __getitem__ with increasing values till it gives index out of range error.





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签