pythonheadache
pythonheadache

Reputation: 106

extract from python dictionary

Lets say my dictionary is the following:

class Airplane:

    def __init__(self, colour, Airplane_type): 
        self.colour = colour
        self.Airplane_type = Airplane_type

    def is_Airplane(self):
        return self.Airplane_type=="Jet"

    def is_orange(self):
          return self.colour=="orange"


class Position:

    def __init__(self, horizontal, vertical):
        self.horizontal = int(horizontal)
        self.vertical = int(vertical)





from airplane import Airplane
from position import Position

Class test():

    def __init__(self):

    self.landings:{Position(1,0) : Airplane("Jet", "orange"),
                   Position(3,0) : Airplane("Boeing", "blue"),}

How do I extract all the orange airplanes and return the number of orange planes for instance.

Upvotes: 0

Views: 183

Answers (3)

Arda Xi
Arda Xi

Reputation: 2666

An elegant way of doing this would be with a list comprehension:

oranges = [plane for plane in self.landings.itervalues()
           if plane.is_orange()]

As M. K. Hunter said, you can call len() on the list to get the number.

Upvotes: 3

M. K. Hunter
M. K. Hunter

Reputation: 1828

This code should give you the result you want:

result = []
keys = []
for key in self.landings:
    if self.landings[key].color == "orange":
        result.append(self.landings[key])
        keys.append(key)
#at the end of the loop, "result" has all the orange planes
#at the end of the loop, "keys" has all the keys of the orange planes
number=len(result) #len(result) gives the number of orange planes

Note that len will work in many situations for the number of x in a list or dictionary.

Upvotes: 1

Blckknght
Blckknght

Reputation: 104722

If you want to find the position of the orange airplanes, you probably want to iterate over the items of the dictionary so that you can both test the color of the plane and at the same time see the position:

orange_plane_positions = [pos for pos, plane in self.landings.values()
                              if plane.is_orange()]

If you're using Python 2 and you have many values in the self.landings dictionary, it might be better to use iteritems rather than items directly (the latter is always best in Python 3).

Note that if this query is something you expect to do frequently, it might make sense to use a different dictionary organization. Rather than indexing by position, index by plane color and store the position as an attribute of the Airplane instance.

Upvotes: 0

Related Questions