1

I need a self nested infinite dictionary of the form

a = {'a': 'a'}
a.update({'b': a})

It works pretty well and values by key 'b' may be retrieved numerous times:

a['b']['b']['b']['b']

Q1: Is there a limit on depth of key 'b'?

Q2: What is the memory size of this object?

martineau
  • 119,623
  • 25
  • 170
  • 301
Andriy
  • 1,270
  • 3
  • 17
  • 35
  • 1
    The object is a two-entry dictionary that holds the string `'a'` and a reference to itself. So, the size is very modest. The number of `['b']`'s is limited by your interpreter. – DYZ Oct 20 '21 at 22:36
  • 1
    There's no limit, because the `dict` itself is not infinite, only self-referential. `a['b'] is a` will be `True`. (There may be a *syntactic* limit on how large an expression you can write, but that's not related to the `dict` itself.) – chepner Oct 20 '21 at 23:13

1 Answers1

1

As DYZ mentioned, since the update is only referencing a, the size is small.

import sys
a = {'a': 'a'}
id(a)                 # 2420845831296
a.update({'b': a})
id(a['b'])            # 2420845831296
sys.getsizeof(a)      # 232 bytes

For the limit, check this question: Can python list and dictionary be nested infinitely?

jak123
  • 318
  • 2
  • 12
  • 2
    It is true that `id(a) = id(a['b'])`. The size 232 bytes is incorrect, I guess. The size of dict cannot be derived by simple `sys.getsizeof(a)`: https://stackoverflow.com/a/30316760 However, the exact object size is not very important here. It is important to know that the size is relatively small. Thanks. – Andriy Oct 20 '21 at 23:03