How to Use a Dot "." to Access Members of Dictionary

How to use a dot . to access members of dictionary?

You can do it using this class I just made. With this class you can use the Map object like another dictionary(including json serialization) or with the dot notation. I hope to help you:

class Map(dict):
"""
Example:
m = Map({'first_name': 'Eduardo'}, last_name='Pool', age=24, sports=['Soccer'])
"""
def __init__(self, *args, **kwargs):
super(Map, self).__init__(*args, **kwargs)
for arg in args:
if isinstance(arg, dict):
for k, v in arg.iteritems():
self[k] = v

if kwargs:
for k, v in kwargs.iteritems():
self[k] = v

def __getattr__(self, attr):
return self.get(attr)

def __setattr__(self, key, value):
self.__setitem__(key, value)

def __setitem__(self, key, value):
super(Map, self).__setitem__(key, value)
self.__dict__.update({key: value})

def __delattr__(self, item):
self.__delitem__(item)

def __delitem__(self, key):
super(Map, self).__delitem__(key)
del self.__dict__[key]

Usage examples:

m = Map({'first_name': 'Eduardo'}, last_name='Pool', age=24, sports=['Soccer'])
# Add new key
m.new_key = 'Hello world!'
# Or
m['new_key'] = 'Hello world!'
print m.new_key
print m['new_key']
# Update values
m.new_key = 'Yay!'
# Or
m['new_key'] = 'Yay!'
# Delete key
del m.new_key
# Or
del m['new_key']

Accessing dictionary keys using dot(.)

By applying your example

class DotDict(dict):
pass

d = DotDict()
d.first_key = 1
d.second_key = 2
print(d.first_key)
print(d.second_key)

you set instance parameters first_key and second_key to your DotDict class but not to the dictionary itself. You can see this, if you just put your dictionary content to the screen:

In [5]: d
Out[5]: {}

So, it is just an empty dict. You may access dictionaries the common way:

In [1]: d={}

In [2]: d['first'] = 'foo'

In [3]: d['second'] = 'bar'

In [4]: d
Out[4]: {'first': 'foo', 'second': 'bar'}

How to use a dot . to access members of dictionary?

You can do it using this class I just made. With this class you can use the Map object like another dictionary(including json serialization) or with the dot notation. I hope to help you:

class Map(dict):
"""
Example:
m = Map({'first_name': 'Eduardo'}, last_name='Pool', age=24, sports=['Soccer'])
"""
def __init__(self, *args, **kwargs):
super(Map, self).__init__(*args, **kwargs)
for arg in args:
if isinstance(arg, dict):
for k, v in arg.iteritems():
self[k] = v

if kwargs:
for k, v in kwargs.iteritems():
self[k] = v

def __getattr__(self, attr):
return self.get(attr)

def __setattr__(self, key, value):
self.__setitem__(key, value)

def __setitem__(self, key, value):
super(Map, self).__setitem__(key, value)
self.__dict__.update({key: value})

def __delattr__(self, item):
self.__delitem__(item)

def __delitem__(self, key):
super(Map, self).__delitem__(key)
del self.__dict__[key]

Usage examples:

m = Map({'first_name': 'Eduardo'}, last_name='Pool', age=24, sports=['Soccer'])
# Add new key
m.new_key = 'Hello world!'
# Or
m['new_key'] = 'Hello world!'
print m.new_key
print m['new_key']
# Update values
m.new_key = 'Yay!'
# Or
m['new_key'] = 'Yay!'
# Delete key
del m.new_key
# Or
del m['new_key']

Dictionary keys with a dot does not work with update()?

I am glad for the input I have got on my questions around parDict, although my original neglect of the difference between "keys" and "identifiers" is very basic. The purpose I have in mind is to simplify command-line interaction with an object-oriented parameter structure. It is a problem of some generality and perhaps here are better solutions than what I suggest below?

Using update() with tuples is attractive, more readable and avoid using a few signs as pointed out at the link @wjandrea posted.
But to use it this way we need to introduce another dictionary, i.e. we have parDict with short unique parameter names and use identifiers and corresponding values, and then introduce parLocation that is a dictionary that relates the short names parameter names to the location object-oriented string.

The solution

parDict = {}
parDict['a'] = 1
parDict['b'] = 2
parDict['group1_b'] = 3

and

parLocation = {}
parLocation['a'] = 'a'
parLocation['b'] = 'b'
parLocation['group1_b'] = 'group1.b'

For command line-interaction I can now write

parDict.update(b=4, group1_b=4)

And for the internal processing where parameter values are brought to the object-oriented system I write something like

for key in parDict.keys(): set(parLocation[key], parDict[key])

where set() is some function that take as arguments parameter "location" and "value".

Since the problem has some generality I though here might be some other better or more direct approach?

Possible to set a Python nested dictionary item using single dot-delimited string path?

You could define a little helper function:

def set(obj, path, value):
*path, last = path.split(".")
for bit in path:
obj = obj.setdefault(bit, {})
obj[last] = value

set(data_dictionary, "user_data.phone", "123")
data_dictionary
# {'user_data': {'first_name': 'Some', 'last_name': 'Guy', 'phone': '123'}}

You can also subclass dict and override __setitem__:

class my_dict(dict):
def __setitem__(self, item, value):
if "." in item:
head, path = item.split(".", 1)
obj = self.setdefault(head, my_dict())
obj[path] = value
else:
super().__setitem__(item, value)

dd = my_dict({
"user_data": {
"first_name": "Some",
"last_name": "Guy",
"phone": "212-111-1234"
}
})

dd["user_data.phone"] = "123"
dd
# {'user_data': {'first_name': 'Some', 'last_name': 'Guy', 'phone': '123'}}

why can't I use '.' to access my dictionary

You cannot access object's items through dot-notation in Python. You're supposed to use braces.

screen.draw(game["img"]["bg"], (0,0)) 


Related Topics



Leave a reply



Submit