7

Is it possible to get a value from a dictionary entry, within that same dictionary? I'd like to build up a list of directories whilst referencing previously added directories..

common_dirs = {
    'root': '/var/tmp',
    'java_path': os.path.join(dict.get('root'), 'java'),
    'application_path': os.path.join(dict.get('java_path'), 'my_app')
}
Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65

3 Answers3

10

Why not update the dictionary:

my_dict = {'root': '/var/tmp'}
my_dict.update({'file': os.path.join(my_dict.get('root'), 'file')})

Don't use dict as a name. You may need the real dict builtin later on.

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
1

No. At the point at which you are filling in the dictionary initializer, the dictionary does not exist, so you cannot reference it!

But in principle there is no reason why a dictionary cannot contain itself as one of the values, as the other answers explain, but you just can't refer to it in its own initializer {}.

daphtdazz
  • 7,754
  • 34
  • 54
0

You could also try using a class instead of a dictionary:

import os

class Paths:
    def __init__(self, root, filename):
        self.root = root
        self.file = os.path.join(self.root, filename)

root = '/var/tmp'
filename = 'file'

p = Paths(root, filename)
print(p.file)
# /var/tmp/file
Alec
  • 1,399
  • 4
  • 15
  • 27
  • That's some crazy overkill, and could potentially break if the rest of OP's code is expecting a dictionary. – Morgan Thrapp Jul 07 '16 at 20:51
  • @MorganThrapp Probably, but that doesn't mean they couldn't be passed in dynamically, assuming this is a minimal verifiable example. – Alec Jul 07 '16 at 20:53
  • 1
    @MorganThrapp Fair enough, I edited the response to show that. I do agree that a class is overkill in all likelihood though! – Alec Jul 07 '16 at 20:56