Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do I do when I need a self referential dictionary?

I'm new to Python, and am sort of surprised I cannot do this.

dictionary = {     'a' : '123',     'b' : dictionary['a'] + '456' } 

I'm wondering what the Pythonic way to correctly do this in my script, because I feel like I'm not the only one that has tried to do this.

EDIT: Enough people were wondering what I'm doing with this, so here are more details for my use cases. Lets say I want to keep dictionary objects to hold file system paths. The paths are relative to other values in the dictionary. For example, this is what one of my dictionaries may look like.

dictionary = {     'user': 'sholsapp',     'home': '/home/' + dictionary['user'] } 

It is important that at any point in time I may change dictionary['user'] and have all of the dictionaries values reflect the change. Again, this is an example of what I'm using it for, so I hope that it conveys my goal.

From my own research I think I will need to implement a class to do this.

like image 639
sholsapp Avatar asked Sep 17 '10 19:09

sholsapp


People also ask

What is the benefit of a DICT dictionary over a list?

It is more efficient to use a dictionary for lookup of elements because it takes less time to traverse in the dictionary than a list. For example, let's consider a data set with 5000000 elements in a machine learning model that relies on the speed of retrieval of data.

Is self a dictionary python?

If you are working with Python, there is no escaping from the word “self”. It is used in method definitions and in variable initialization. The self method is explicitly used every time we define a method.

Why we need to use dictionary when we already have list?

A dictionary is a mutable object. The main operations on a dictionary are storing a value with some key and extracting the value given the key. In a dictionary, you cannot use as keys values that are not hashable, that is, values containing lists, dictionaries or other mutable types.

What is required in a valid dictionary key?

Second, a dictionary key must be of a type that is immutable. For example, you can use an integer, float, string, or Boolean as a dictionary key. However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable.


1 Answers

No fear of creating new classes - You can take advantage of Python's string formating capabilities and simply do:

class MyDict(dict):    def __getitem__(self, item):        return dict.__getitem__(self, item) % self  dictionary = MyDict({      'user' : 'gnucom',     'home' : '/home/%(user)s',     'bin' : '%(home)s/bin'  })   print dictionary["home"] print dictionary["bin"] 
like image 147
jsbueno Avatar answered Sep 26 '22 06:09

jsbueno