473,563 Members | 2,696 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Getting a dictionary from an object

Hello.

I would like to have a quick way to create dicts from object, so that a
call to foo['bar'] would return obj.bar.

The following works, but I would prefer to use a built-in way if one
exists. Is there one?

Thanks in advance.

class dictobj(dict):
"""
class dictobj(dict):
A dictionary d with an object attached to it,
which treats d['foo'] as d.obj.foo.
"""
def __init__(self, obj):
self.obj = obj
def __getitem__(sel f, key):
return self.obj.__geta ttribute__(key)

--
Thanos Tsouanas .: My Music: http://www.thanostsouanas.com/
http://thanos.sians.org/ .: Sians Music: http://www.sians.org/
Jul 23 '05 #1
31 2551
Thanos Tsouanas a écrit :
Hello.

I would like to have a quick way to create dicts from object, so that a
call to foo['bar'] would return obj.bar.

The following works, but I would prefer to use a built-in way if one
exists. Is there one?

Thanks in advance.

class dictobj(dict):
"""
class dictobj(dict):
A dictionary d with an object attached to it,
which treats d['foo'] as d.obj.foo.
"""
def __init__(self, obj):
self.obj = obj
def __getitem__(sel f, key):
return self.obj.__geta ttribute__(key)


I'd replace this last line with:
return getattr(self.ob j, key)
Now given your specs, I don't see what's wrong with your solution.
Jul 23 '05 #2
On Sat, Jul 23, 2005 at 11:30:19AM +0200, Bruno Desthuilliers wrote:
Thanos Tsouanas a écrit :
class dictobj(dict):
"""
class dictobj(dict):
A dictionary d with an object attached to it,
which treats d['foo'] as d.obj.foo.
"""
def __init__(self, obj):
self.obj = obj
def __getitem__(sel f, key):
return self.obj.__geta ttribute__(key)


I'd replace this last line with:
return getattr(self.ob j, key)

Now given your specs, I don't see what's wrong with your solution.


I just dont want to use my class, if one already exists in the
libraries (or any other way to achieve the same thing), that's all ;)

Thanks for the tip.

--
Thanos Tsouanas .: My Music: http://www.thanostsouanas.com/
http://thanos.sians.org/ .: Sians Music: http://www.sians.org/
Jul 23 '05 #3
On Sat, 23 Jul 2005 11:48:27 +0300, Thanos Tsouanas wrote:
Hello.

I would like to have a quick way to create dicts from object, so that a
call to foo['bar'] would return obj.bar.
That looks rather confusing to me. Why not just call obj.bar, since it
doesn't look like you are actually using the dictionary at all?
The following works, but I would prefer to use a built-in way if one
exists. Is there one?

Thanks in advance.

class dictobj(dict):
"""
class dictobj(dict):
A dictionary d with an object attached to it,
which treats d['foo'] as d.obj.foo.
"""
def __init__(self, obj):
self.obj = obj
def __getitem__(sel f, key):
return self.obj.__geta ttribute__(key)


I don't think this is particularly useful behaviour. How do you use it?

py> D = dictobj("hello world")
py> D
{}
py> D.obj
'hello world'
py> D["food"] = "spam"
py> D
{'food': 'spam'}
py> D["food"]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 5, in __getitem__
AttributeError: 'str' object has no attribute 'food'
--
Steven.
Jul 23 '05 #4
Steven D'Aprano <st***@REMOVETH IScyber.com.au> writes:
On Sat, 23 Jul 2005 11:48:27 +0300, Thanos Tsouanas wrote:
Hello.

I would like to have a quick way to create dicts from object, so that a
call to foo['bar'] would return obj.bar.


That looks rather confusing to me. Why not just call obj.bar, since it
doesn't look like you are actually using the dictionary at all?


Well, I needed exactly this functionality last week. I have a
collection of (rather messy) classes that have a slew of attributes as
values. I would have used a dictionary for this, but I didn't write
the code.

I have to be able to display these objects (in HTML, if it matters),
and have as a requirement that the format string live in a database.

My solution didn't look to different from dictobj. There's some extra
mechanism to fetch the format string from the database, and some
formatting of the attribute based on meta-information in the object,
but it's the same basic idea.
class dictobj(dict):
"""
class dictobj(dict):
A dictionary d with an object attached to it,
which treats d['foo'] as d.obj.foo.
"""
def __init__(self, obj):
self.obj = obj
def __getitem__(sel f, key):
return self.obj.__geta ttribute__(key)


I don't think this is particularly useful behaviour. How do you use it?


def __str__(self):
return self._format % self
<mike
--
Mike Meyer <mw*@mired.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Jul 23 '05 #5
On Sat, Jul 23, 2005 at 11:22:21PM +1000, Steven D'Aprano wrote:
On Sat, 23 Jul 2005 11:48:27 +0300, Thanos Tsouanas wrote:
Hello.

I would like to have a quick way to create dicts from object, so that a
call to foo['bar'] would return obj.bar.


That looks rather confusing to me. Why not just call obj.bar, since it
doesn't look like you are actually using the dictionary at all?
[...]


I don't think this is particularly useful behaviour. How do you use it?


print foo %do

where do is a dictobj object...

--
Thanos Tsouanas .: My Music: http://www.thanostsouanas.com/
http://thanos.sians.org/ .: Sians Music: http://www.sians.org/
Jul 23 '05 #6
Thanos Tsouanas wrote:
I would like to have a quick way to create dicts from object, so that a
call to foo['bar'] would return obj.bar.

The following works, but I would prefer to use a built-in way if one
exists. Is there one?


Maybe I'm not understanding your problem, but have you looked at the
builtin "vars()"?

STeVe
Jul 24 '05 #7
On Sat, 23 Jul 2005 13:50:36 -0400, Mike Meyer wrote:
I don't think this is particularly useful behaviour. How do you use it?


def __str__(self):
return self._format % self


That doesn't work. It calls self.__str__ recursively until Python halts
the process.
class Thing(dict): .... _format = "Thing %s is good."
.... def __str__(self):
.... return self._format % self
.... X = Thing()
X # calls __repr__ so is safe {} str(X) # not safe

File "<stdin>", line 4, in __str__
File "<stdin>", line 4, in __str__
...
File "<stdin>", line 4, in __str__
File "<stdin>", line 4, in __str__
RuntimeError: maximum recursion depth exceeded
--
Steven.

Jul 24 '05 #8
On Sun, 24 Jul 2005 02:09:54 +0300, Thanos Tsouanas wrote:
On Sat, Jul 23, 2005 at 11:22:21PM +1000, Steven D'Aprano wrote:
On Sat, 23 Jul 2005 11:48:27 +0300, Thanos Tsouanas wrote:
> Hello.
>
> I would like to have a quick way to create dicts from object, so that a
> call to foo['bar'] would return obj.bar.


That looks rather confusing to me. Why not just call obj.bar, since it
doesn't look like you are actually using the dictionary at all?
> [...]


I don't think this is particularly useful behaviour. How do you use it?


print foo %do

where do is a dictobj object...


Are you telling me that the ONLY thing you use dictobj objects for is to
print them?

I don't think so. I do know how to print an object, amazingly.

Perhaps you would like to explain how you use the rest of the
functionality of the dictobj, instead of taking my words out of context
and giving an inane answer.

Why jump through all those hoops to get attributes when Python already
provides indexing and attribute grabbing machinery that work well? Why do
you bother to subclass dict, only to mangle the dict __getitem__ method so
that you can no longer retrieve items from the dict?
--
Steven.

Jul 24 '05 #9
On Sun, Jul 24, 2005 at 01:43:43PM +1000, Steven D'Aprano wrote:
On Sun, 24 Jul 2005 02:09:54 +0300, Thanos Tsouanas wrote:

print foo %do

where do is a dictobj object...
Are you telling me that the ONLY thing you use dictobj objects for is to
print them?


I'm sorry to disappoint you, but yes. When you have a long text
template to fill-out, with lots of %(foo)s, and all those foos are
attributes of an object, it really helps to have dictobj.
I don't think so. I do know how to print an object, amazingly.
Please, tell me, how would you print it in my case?
Perhaps you would like to explain how you use the rest of the
functionality of the dictobj, instead of taking my words out of context
and giving an inane answer.
I dont see _ANY_ other functionality in the dictobj class. Do you?
Why jump through all those hoops to get attributes when Python already
provides indexing and attribute grabbing machinery that work well? Why do
you bother to subclass dict, only to mangle the dict __getitem__ method so
that you can no longer retrieve items from the dict?


Because *obviously* I don't know of these indexing and attribute
grabbing machineries you are talking about in my case. If you cared to
read my first post, all I asked was for the "normal", "built-in" way to
do it. Now, is there one, or not?

--
Thanos Tsouanas .: My Music: http://www.thanostsouanas.com/
http://thanos.sians.org/ .: Sians Music: http://www.sians.org/
Jul 24 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
3576
by: none | last post by:
or is it just me? I am having a problem with using a dictionary as an attribute of a class. This happens in python 1.5.2 and 2.2.2 which I am accessing through pythonwin builds 150 and 148 respectively In the sample code you see that I have class Item and class Dict class Dict contains a dictionary called items. The items dictionary...
26
4030
by: Alan Silver | last post by:
Hello, I have a server running Windows Server 2003, on which two of the web sites use the MegaBBS ASP forum software. Both sites suddenly developed the same error, which seems to be connected to the dictionary object. After some tinkering, I whittled it down to the following (complete) ASP... <%@ CodePage=65001 Language="VBScript"%>
5
14790
by: David Rasmussen | last post by:
If I have a string that contains the name of a function, can I call it? As in: def someFunction(): print "Hello" s = "someFunction" s() # I know this is wrong, but you get the idea... /David
2
15909
by: ESPNSTI | last post by:
Hi, I'm trying to use a generics dictionary with a key class that implements and needs IComparable<>. However when I attempt to use the dictionary, it doesn't appear to use the IComparable<> to find the key. In the example below, accessing the dictionary by using the exact key object that was used to add to the dictionary works. (see code...
2
3410
by: jg | last post by:
I was trying to get custom dictionary class that can store generic or string; So I started with the example given by the visual studio 2005 c# online help for simpledictionay object That seem to miss a few things including #endregion directive and the ending class } Is there not a simple way like in dotnet vb? I managed to get the...
4
2315
by: Betina Andersen | last post by:
I have a dictionary object, then I create a new dictionary object and sets it equal to my original, then I pass the new dictionary object to a function that changes some of my values - but then my original dictionary also gets changed and that was not the intention, can someone explain to me why it behaves that way and how do I avoid it, så I...
5
21570
by: randy1200 | last post by:
I have the following: Dictionary<object, stringd = new Dictionary<object, string>(); I can add entries to the dictionary, and I can loop through the entries I've added to the Dictionary. This all works great. My question is: I'd like to find a way to get just the first key, without looping through the whole Dictionary. I tried the code...
4
14677
by: NullQwerty | last post by:
Hi folks, I have a Dictionary which contains a string key and an object value. I want the object value to point to a property in my class and I want it to be by reference, so that later on I can change the value of the property through the dictionary. I am having difficulty making the value be by reference. Is this possible? I've even...
6
10163
by: GiJeet | last post by:
hello, I'm trying to use a dictionary as a class member. I want to use a property to get/set the key/value of the dictionary but I'm confused as how to use a dictionary as a property. Since there are 2 parts, I don't know how to setup the get/sets. I tried searching but could not find any examples. I'd appreciate an example of how to get/...
0
7664
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7885
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8106
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7638
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6250
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5213
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3642
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1198
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
923
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.