Skip to content

Instantly share code, notes, and snippets.

@jtallieu
Created August 13, 2017 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jtallieu/c22cb72b9e7f022a8a5577835f5f35aa to your computer and use it in GitHub Desktop.
Save jtallieu/c22cb72b9e7f022a8a5577835f5f35aa to your computer and use it in GitHub Desktop.
Dict like data structure for operating on tag results from Clarifai - where a list of tags and scores are grouped by models.
class TagMap(dict):
"""
Interpret tag values {<model>:{name: value}, ..} and wrap to get '.' access to the value.
data = {'general': [('joey', 10), ('x y', 22)], 'een': ('ken', 30)]}
tm = TagMap(data)
print tm.joey
print tm['x y']
print tm.x_y
if tm.joey < tm.ken: print "YES"
x = tm.joey - tm.ken
tm.x_y = 33
print tm['x y']
"""
def __init__(self, *args, **kwargs):
super(TagMap, self).__init__(*(), **{})
for arg in args:
if isinstance(arg, dict):
for k, v in arg.iteritems():
if isinstance(v, list):
for tup in v:
_k = tup[0]
_v = tup[1]
self[_k] = _v if self.get(_k, 0) < _v else self.get(_k, 0)
def __getattr__(self, attr):
key = attr.replace("_", " ")
return self.get(key, 0)
def __setattr__(self, key, value):
self.__setitem__(key.replace("_", " "), value)
def __setitem__(self, key, value):
super(TagMap, self).__setitem__(key, value)
self.__dict__.update({key.replace("_", " "): value})
def __delattr__(self, item):
self.__delitem__(item)
def __delitem__(self, key):
super(TagMap, self).__delitem__(key)
del self.__dict__[key.replace("_", " ")]
from pprint import pprint
from iris.intel import TagMap
data = {
'general': [
('joey', 10), ('ben', 20), ('x y', 22)
],
'een': [
('ken', 30), ('joey', 50)
],
'sdf': [
('joey', 10)
]
}
m = TagMap(data)
print m.joey, m.ben
print m.joey < m.ben
print m['x y']
print m.x_y
m.x_y = 33
print m['x y']
print m.p
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment