-1

I am doing some python programming and like the dictionaries in python. I am wondering if there is a compact way to access the elements of a dictionary within the dictionary itself? For example see the following code:

MyDict = {'n':1, 's':2}
MyDict.update({'x' : MyDict['n']*2})

Often the dictionary names are long so it would be very convenient to have something like:

MyDict.update({'x' : self['n']*2})

Any idea if there is such a compact form?

A.J.
  • 31
  • 7
  • 1
    No, there isn't. You could alias the dictionary beforehand if you wanted to shorten a specific line; `dct = my_dict_with_a_very_long_name_i_do_not_want_to_keep_writing`, *then* `dct.update({'x': dct['n'] * 2})`. But the argument to `update` is evaluated *before* the method gets called, it's **not** *"within the dictionary itself"*. – jonrsharpe Sep 13 '18 at 11:49

1 Answers1

0

Btw the easiest way is still:

d = {'n':1, 's':2}
d['x']=d['n']*2

And if wanted self, just rename d to self

Then don't want long names, just don't do long names

Or a way is:

foofoofooblahblahbarbar={'n':1, 's':2}
d=foofoofooblahblahbarbar
d['x']=d['n']*2
...

After all then when yo do:

print(foofoofooblahblahbarbar)

it will be the same as d

U13-Forward
  • 69,221
  • 14
  • 89
  • 114