pythonpython-2.7

Python (2.7.8) : Phonebook, Multiple keys with the same value (Alias)


class Phonebook:

      def __init__(self):
          self.bok={('eddie','ed'): '1234',('peter','pete'): '4321'}

      def add(self, name, number):
          if name in self.bok.keys():                     
             print "The name does already exist."
          else:
             self.bok[name] = number                      
             print self.bok

      def lookup(self, name):
          for item in self.bok.keys():
              if name in item:
                 print "Name :", name
                 print "Telephone number: ", self.bok[item]

      def alias(self, name, nick):
          self.bok[name, nick] = self.bok[name]
          del self.bok[name]

      def change(self, name, number):
          for item in self.bok.keys():
              if name in item:
                 print "test"

So, what I would like to do is add "Alias" to a chosen name like:

Alias eddie ed (Adds the alias "ed" to the name "eddie")

But the problem here is that it becomes a Tuple in the dictionary after I've done that so I can't add more Alias'es to the same name with the current function because it only works for Dictionary and not Tuples, like:

Alias ed eddinator (Adds the alias "eddinator" to the name "ed" which is connected to eddie) ==> Gives me error.

And then the same problems appears for Change. Change = The alias'es should always have the same number as the "head" name so if I change eddie's number to 9876 then ed and eddinator should also have it. (Multiple keys with same value)

The lookup function is working. I'm not really sure this is the easiest way but its currently the only way I've found so far!


Solution

  • Have the aliases point to the head names, and the have the head names point to the phone number:

    class Phonebook:
    
        def __init__(self):
            self.bok = {'eddie': 1234,
                        'ed': 'eddie',
                        'peter': 4321, 
                        'pete': 'peter'}
    
    
        def add(self, name, number):
            if name in self.bok.keys():                     
                print "The name does already exist."
            else:
                self.bok[name] = int(number)
                print self.bok
    
    
        def lookup(self, name):
            val = self.bok[name]
            while isinstance(val, str):
                val = self.bok[val]
    
            print "Name :", name
            print "Telephone number: ", val
    
    
        def alias(self, name, nick):
            if nick in self.bok:
                print 'that alias already exists'
                return
            self.bok[nick] = name
    
    
        def change(self, name, number):
            while isinstance(self.bok[name], str):
                name = self.bok[name]
            self.bok[name] = int(number)