0

Consider the following python class:

class Event(Document):
  name = StringField()
  time = DateField()
  location = GeoPointField()

  def __unicode__(self):
    return self.name

Now I create a list of Events:

x = [Event(name='California Wine Mixer'),
  Event(name='American Civil War'),
  Event(name='Immaculate Conception')]

Now I want to add only unique events by searching via the event name. How is this done with the boolean in syntax?

The following is incorrect:

a = Event(name='California Wine Mixer')
if a.name in x(Event.name):
  x.append(a)

1 Answer 1

3

By unique I think you want something like "if a.name not in x(Event.name):", which can be written as

if not any(y.name == a.name for y in x):
  ...

But if the name acts as an index, it is better to use a dictionary to avoid the O(N) searching time and the more complex interface.

event_list = [Event(name='California Wine Mixer'), ...]

event_dict = dict((b.name, b) for b in event_list)
# ignore event_list from now on.

....

a = Event(name='California Wine Mixer')
event_dict.setdefault(a.name, a)
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, that's what I meant. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.