Home > database >  String interning in dictionary keys
String interning in dictionary keys

Time:10-09

Does string interning work on dict keys in python ? Suppose I have a dictionary of dictionaries and each of the dictionaries in the dictionary has the same keys.

e.g:

dict1 -> keys 'a','b','c' dict2 -> keys 'a','b','c'

Are the keys for those dictionaries referenced in the same memory place? or the string interning does not come implicitly for those strings ?

CodePudding user response:

Yes, strings and integers are interned, but only small strings and integers.

>>> list1 = ['a', 'b', 'c', 'longer and more complicated string']
>>> list2 = ['a', 'b', 'c', 'longer and more complicated string']
>>> list1[0] is list2[0]
True
>>> list1[1] is list2[1]
True
>>> list1[2] is list2[2]
True
>>> list1[3] is list2[3]
False

Two dicts with the same keys are allowed to have completely different values, however - the key-value mapping is tied to the dict's instance (and also to the hashes of the keys, moreso than the keys themselves), not to the key's instance, and dicts are not interned at all.

>>> dict1 = {'a': 1, 'b': 2}
>>> dict2 = {'a': 3, 'b': 4}
>>> for (key1, key2) in zip(dict1.keys(), dict2.keys()):
...     print(key1 is key2, end="; ")
...     print(dict1[key1] is dict2[key2])
... 
True; False
True; False

If you wish to save memory by having only one key-value mapping, have you considered making the dictionary values be tuples? e.g.

# instead of
dict1[key] -> value1
dict2[key] -> value2

# do
dictx[key] -> (value1, value2)
  • Related