Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Object as Dictionary Value [closed]

Tags:

python

So I have the following code in which the value of a dictionary is an object, and the key to that object is an item in the object as such:

class MyObject():
    def getName(self):
       return self.name

    def getValue(self):
       return self.value

    def __init__(self,name, value):
       self.name = name
       self.value = value


dict = {}
object = MyObject('foo', 2) //foo is the name, 2 is the value
dict[object.getName()] = object

However I cannot access the object like so:

>>>print dict['foo'].getValue()
<bound method object.getValue of <__main__.object instance at 0xFOOBAR000 >>

Is there a way I can access the object in this manner?

EDIT:

I don't know why but my code finally decided to start working, so for anyone haveing similar issues the above code is valid and should work. My current version of Python is 2.7.3

like image 734
Blackninja543 Avatar asked Nov 13 '12 20:11

Blackninja543


People also ask

Can an object be a value in dictionary Python?

A dictionary value can be any type of object Python supports, including mutable types like lists and dictionaries, and user-defined objects, which you will learn about in upcoming tutorials.

Can dictionary value be an object?

A dictionary key must be an immutable object. A dictionary value can be any object.

Can you store objects in Python dictionary?

The Python list stores a collection of objects in an ordered sequence. In contrast, the dictionary stores objects in an unordered collection. However, dictionaries allow a program to access any member of the collection using a key – which can be a human-readable string.

How do you remove an object from a dictionary?

Because key-value pairs in dictionaries are objects, you can delete them using the “del” keyword. The “del” keyword is used to delete a key that does exist.


1 Answers

You always need to include parentheses when calling functions, so write:

dict['foo'].getValue()

Also, the getValue method should accept a self parameter and access instance attributes through it:

def getValue(self):
    return self.value

Finally, that programming style, where every attribute is accompanied by a "getter", is discouraged in Python. It is easy enough to implement calculated slots, so there is no need for getters.

Names such as dict and object are also highly discouraged because they conflict with built-in types of the same name.

EDIT
The code was edited in the meantime, rendering some of the above remarks obsolete. The latest version of the posted code appears to work just fine when pasted into Python.

like image 53
user4815162342 Avatar answered Sep 18 '22 17:09

user4815162342