Quantcast
Channel: Accessing dict keys like an attribute? - Stack Overflow
Browsing latest articles
Browse All 35 View Live

Answer by Gerard ONeill for Accessing dict keys like an attribute?

I'm gonna be a party pooper (hat tip Arnold).YOU SHOULD NOT WANT TO DO THIS. I'm sure you know this, but an attribute is a feature of the object (in this case the dictionary), while a key is a hash...

View Article



Answer by Hans for Accessing dict keys like an attribute?

First, I would like to thank @Kimvais for his genius answer.I added some stuff to it.Create a file, called punktdict.pyimport sysdictconfig = sys.modules[__name__]# Create a reference to the current...

View Article

Answer by Marquinho Peli for Accessing dict keys like an attribute?

Sorry to add one more, but this one addresses the subdicts and correct AttributeError, although being very simple:class DotDict(dict): def __init__(self, d: dict = {}): super().__init__() for key,...

View Article

Answer by s2t2 for Accessing dict keys like an attribute?

Use SimpleNamespace:from types import SimpleNamespaceobj = SimpleNamespace(color="blue", year=2050)print(obj.color) #> "blue"print(obj.year) #> 2050EDIT / UPDATE: a closer answer to the OP's...

View Article

Answer by hokage555 for Accessing dict keys like an attribute?

After not being satisfied with the existing options for the reasons below I developed MetaDict. It behaves exactly like dict but enables dot notation and IDE autocompletion without the shortcomings and...

View Article


Answer by Hyperx837 for Accessing dict keys like an attribute?

this answer is taken from the book Fluent Python by Luciano Ramalho. so credits to that guy.class AttrDict:"""A read-only façade for navigating a JSON-like object using attribute notation""" def...

View Article

Answer by Elmahy for Accessing dict keys like an attribute?

The easiest way is to define a class let's call it Namespace. which uses the object dict.update() on the dict. Then, the dict will be treated as an object.class Namespace(object):''' helps referencing...

View Article

Answer by DeusXMachina for Accessing dict keys like an attribute?

I found myself wondering what the current state of "dict keys as attr" in the python ecosystem. As several commenters have pointed out, this is probably not something you want to roll your own from...

View Article


Answer by mujjiga for Accessing dict keys like an attribute?

This is what I useargs = {'batch_size': 32,'workers': 4,'train_dir': 'train','val_dir': 'val','lr': 1e-3,'momentum': 0.9,'weight_decay': 1e-4 }args = namedtuple('Args',...

View Article


Answer by Alon Barad for Accessing dict keys like an attribute?

You can use dict_to_objhttps://pypi.org/project/dict-to-obj/It does exactly what you asked forFrom dict_to_obj import DictToObja = {'foo': True}b = DictToObj(a)b.fooTrue

View Article

Answer by pylang for Accessing dict keys like an attribute?

What would be the caveats and pitfalls of accessing dict keys in this manner?As @Henry suggests, one reason dotted-access may not be used in dicts is that it limits dict key names to python-valid...

View Article

Image may be NSFW.
Clik here to view.

Answer by ramazan polat for Accessing dict keys like an attribute?

How about Prodict, the little Python class that I wrote to rule them all:)Plus, you get auto code completion, recursive object instantiations and auto type conversion!You can do exactly what you asked...

View Article

Answer by user2804865 for Accessing dict keys like an attribute?

Just to add some variety to the answer, sci-kit learn has this implemented as a Bunch:class Bunch(dict): """ Scikit Learn's container object Dictionary-like object that exposes its keys as attributes....

View Article


Answer by kadee for Accessing dict keys like an attribute?

Let me post another implementation, which builds upon the answer of Kinvais, but integrates ideas from the AttributeDict proposed in http://databio.org/posts/python_AttributeDict.html.The advantage of...

View Article

Answer by mizu for Accessing dict keys like an attribute?

EDIT: NeoBunch is depricated, Munch (mentioned above) can be used as a drop-in replacement. I leave that solution here though, it can be useful for someone.As noted by Doug there's a Bunch package...

View Article


Answer by Bruno Rocha - rochacbruno for Accessing dict keys like an attribute?

Solution is:DICT_RESERVED_KEYS = vars(dict).keys()class SmartDict(dict):""" A Dict which is accessible via attribute dot notation""" def __init__(self, *args, **kwargs):""" :param args: multiple dicts...

View Article

Answer by h_vm for Accessing dict keys like an attribute?

class AttrDict(dict): def __init__(self): self.__dict__ = selfif __name__ == '____main__': d = AttrDict() d['ray'] = 'hope' d.sun = 'shine'>>> Now we can use this . notation print d['ray']...

View Article


Answer by Ben Usman for Accessing dict keys like an attribute?

Here's a short example of immutable records using built-in collections.namedtuple:def record(name, d): return namedtuple(name, d.keys())(**d)and a usage example:rec = record('Model', {'train_op':...

View Article

Answer by epool for Accessing dict keys like an attribute?

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 help you:class...

View Article

Answer by Deacon for Accessing dict keys like an attribute?

Wherein I Answer the Question That Was AskedWhy doesn't Python offer it out of the box?I suspect that it has to do with the Zen of Python: "There should be one -- and preferably only one -- obvious way...

View Article

Answer by DylanYoung for Accessing dict keys like an attribute?

This isn't a 'good' answer, but I thought this was nifty (it doesn't handle nested dicts in current form). Simply wrap your dict in a function:def make_funcdict(d=None, **kwargs) def funcdict(d=None,...

View Article


Answer by gonz for Accessing dict keys like an attribute?

This doesn't address the original question, but should be useful for people that, like me, end up here when looking for a lib that provides this functionality.Addict it's a great lib for this:...

View Article


Answer by Yuri Astrakhan for Accessing dict keys like an attribute?

Apparently there is now a library for this - https://pypi.python.org/pypi/attrdict - which implements this exact functionality plus recursive merging and json loading. Might be worth a look.

View Article

Answer by lindyblackburn for Accessing dict keys like an attribute?

You can pull a convenient container class from the standard library:from argparse import Namespaceto avoid having to copy around code bits. No standard dictionary access, but easy to get one back if...

View Article

Answer by Rafe for Accessing dict keys like an attribute?

I created this based on the input from this thread. I need to use odict though, so I had to override get and set attr. I think this should work for the majority of special uses.Usage looks like this:#...

View Article


Answer by Kimvais for Accessing dict keys like an attribute?

Update - 2020Since this question was asked almost ten years ago, quite a bit has changed in Python itself since then.While the approach in my original answer is still valid for some cases, (e.g. legacy...

View Article

Answer by Ryan for Accessing dict keys like an attribute?

Caveat emptor: For some reasons classes like this seem to break the multiprocessing package. I just struggled with this bug for awhile before finding this SO: Finding exception in python multiprocessing

View Article

Answer by slacy for Accessing dict keys like an attribute?

From This other SO question there's a great implementation example that simplifies your existing code. How about:class AttributeDict(dict): __slots__ = () __getattr__ = dict.__getitem__ __setattr__ =...

View Article

Answer by Senthil Kumaran for Accessing dict keys like an attribute?

tuples can be used dict keys. How would you access tuple in your construct?Also, namedtuple is a convenient structure which can provide values via the attribute access.

View Article



Answer by David W for Accessing dict keys like an attribute?

No need to write your own assetattr() and getattr() already exist.The advantage of class objects probably comes into play in class definition and inheritance.

View Article

Answer by tallseth for Accessing dict keys like an attribute?

It doesn't work in generality. Not all valid dict keys make addressable attributes ("the key"). So, you'll need to be careful.Python objects are all basically dictionaries. So I doubt there is much...

View Article

Answer by PrettyPrincessKitty FS for Accessing dict keys like an attribute?

What if you wanted a key which was a method, such as __eq__ or __getattr__?And you wouldn't be able to have an entry that didn't start with a letter, so using 0343853 as a key is out.And what if you...

View Article

Answer by Hery for Accessing dict keys like an attribute?

You can have all legal string characters as part of the key if you use array notation.For example, obj['!#$%^&*()_']

View Article


Accessing dict keys like an attribute?

I find it more convenient to access dict keys as obj.foo instead of obj['foo'], so I wrote this snippet:class AttributeDict(dict): def __getattr__(self, attr): return self[attr] def __setattr__(self,...

View Article

Answer by Alvin Shaita for Accessing dict keys like an attribute?

I get what you're trying to achieve. There are python modules that do the same.You can checkout attridict, it does exactly that. With it you can access dict objects like attributes. Very helpful when...

View Article
Browsing latest articles
Browse All 35 View Live




Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>
<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596344.js" async> </script>