Chris
Chris

Reputation: 25

How do i store multiple object attibutes to a single dictionary key?

I'm fairly new to the world of python and programming in general, and its rare that i get up the nerve to ask questions, but I'm stomped so i thought id suck it up and ask for help.

I'm making an Address book.

class Person():

    def __init__(self,name,number,email):
        self.name = name
        self.number = number
        self.email = email
contact = Person('Mike','1-800-foo-spam','[email protected]')

My question is how would go about storing all these attributes in a dictionary with contact.name as the key and contact.number and contact.email as the values.

Bonus question. Should the dictionary be outside the class, perhaps in the main function? or Does it need to be a class variable(not completely sure how those work) or an object variable

something like

self.storage = {}

Any help would be greatly appreciated.

Thank you!

Upvotes: 0

Views: 4174

Answers (3)

Vadim
Vadim

Reputation: 633

If I put this information in a dictionary, I would do it like that:

class Person():

    def __init__(self,name,number,email):
        self.name = name
        self.number = number
        self.email = email
        self.storage = {self.name: [self.number, self.email]}

    def getStorage(self):
        return self.storage

contact = Person('Mike','1-800-foo-spam','[email protected]')

print contact.storage
# or
print contact.getStorage()

But the whole idea of a dictionary is to have a number of keys and corresponding values. In this example, it always will be one only. So, another schema comes to my mind:

class Person():

    def __init__(self,name,number,email):
        self.name = name
        self.number = number
        self.email = email

# creating some example contacts        
c1 = Person('Mike','1-800-foo-spam','[email protected]')
c2 = Person('Jim','1-700-foo-spam','[email protected]')
c3 = Person('Kim','1-600-foo-spam','[email protected]')

# creating a dictionary to fill it with c1..cn contacts
contacts = {}

# helper function to automate dictionary filling
def contactToDict(list_of_contacts):
    for item in list_of_contacts:
        contacts[item.name] = (item.number, item.email)

contactToDict([c1, c2, c3])

"""
expected output:
Mike: ('1-800-foo-spam', '[email protected]')
Jim: ('1-700-foo-spam', '[email protected]')
Kim: ('1-600-foo-spam', '[email protected]')
"""
for key, val in contacts.items():
    print str(key) + ": " + str(val)

The answer to the title of the question: a value should be a type of object with allows to have a "list" inside (i.e. list, tuple, another dictionary or custom type object having a number of attributes.)

Upvotes: 1

SuperBiasedMan
SuperBiasedMan

Reputation: 9969

If you wanted to make it a class variable, you'd just need to create an empty dictionary as part of the Person class:

class Person():

    storage = {}

Then in __init__ you can store the new person's info in that dictionary:

def __init__(self,name,number,email):
    self.name = name
    self.number = number
    self.email = email
    Person.storage[name] = (number, email)

As you can see class attributes are accessed with the classname, but otherwise like any other attribute. You could store them as a tuple or a list if you need to update them. However if you intend to make changes, it might be better to store the actual Person object, to save having to update Person.storage and the actual person at the same time. This is even easier to do:

def __init__(self,name,number,email):
    self.name = name
    self.number = number
    self.email = email
    Person.storage[name] = self

self refers to the instance of Person that's being created with __init__. That's Mike in your example. Then you could access their values by attribute:

Person.storage["Mike"].number

Also as Kevin pointed out in a comment you might want to detect if the key already exists to avoid overwriting an old entry (eg. if there's already a Mike in the dictionary):

    self.email = email
    if name in Person.storage:
        # Make unique name
    Person.storage[name] = (number, email)

Upvotes: 0

John Petry
John Petry

Reputation: 16

You can pretty easily have a dictionary with tuples as the values.

a = {}
a["bob"] = ("1-800-whatever","[email protected]")

Upvotes: 0

Related Questions