views:

200

answers:

2

I have a class in a module I that reads a plist (XML) file and returns a dict. This is extremely convenient because I can say something like:

Data.ServerNow.Property().DefaultChart

This returns a property dictionary, specifically the value for DefaultChart. Very elegant. However, assembling a dictionary this way fails:

dict={'Data': 'text1', 'Name':'text2', 'Place':'text3]}

dict looks exactly like the Plist dict. But when I say

print TextNow.Data().Name

I get error

 'dict' object has no attribute 'Name'

But if I say

print TextNow.Data()['Name']

suddenly it works!

Can someone explain this behavior? Is there a way to convert a dict to an XML-ish dict?

+1  A: 

It doesn't work because the dot operator is not proper accessor syntax for python dictionaries. You;re trying to treat it as an object and access a property, rather than accessing a data member of the data structure.

phoebus
Thanks. Turns out it was easier to write the plist and load that file into a dict, which I had to do anyway.
Gnarlodious
A: 

You can use getattr redefinition to treat dictionary keys as attributes, e.g.:

class xmldict(dict):
    def __getattr__(self, attr):
        try:
            return object.__getattribute__(self, attr)
        except AttributeError:
            if attr in self:
                return self[attr]
            else:
                raise

So, for example if you will have following dict:

dict_ = {'a':'some text'}

You can do so:

>> print xmldict(dict_).a
some text
>> print xmldict(dict_).NonExistent
Traceback (most recent call last):
  ...
AttributeError: 'xmldict' object has no attribute 'NonExistent'
Mihail