Memory-usage of dictionary in Python?

前端 未结 3 2086
广开言路
广开言路 2021-01-01 15:44

I am slightly confused when I use the getsizeof method in the sys module for dictionaries. Below I have created a simple dictionary of two strings.

3条回答
  •  Happy的楠姐
    2021-01-01 16:33

    The recursive getsizeof would get the actual size, but if you have multiple layers of dictionaries and only want to get a rough estimate. The json comes handy.

    >>> first = 'abc'*1000
    >>> second = 'def'*1000
    >>> my_dictionary = {'first': first, 'second': second}
    >>> getsizeof(first)
    3049
    >>> getsizeof(second)
    3049
    >>> getsizeof(my_dictionary)
    288
    >>> getsizeof(json.dumps(my_dictionary))
    6076
    >>> size = getsizeof(my_dictionary)
    >>> size += sum(map(getsizeof, my_dictionary.values())) + sum(map(getsizeof, my_dictionary.keys()))
    >>> size
    6495
    

提交回复
热议问题