When the key is a tuple in dictionary in Python

Question:

I’m having troubles understanding this. I have a dictionary, where the key is a tuple consisting of two strings. I want to lowercase the first string in this tuple, is this possible?

Asked By: user2795095

||

Answers:

You would have to change the string to lowercase before putting it into the tuple. Tuples are read-only after they are created.

Answered By: aldo

Since a tuple is immutable, you need to remove the old one and create a new one. This works in Python 2 and 3, and it keeps the original dict:

>>> d = {('Foo', 0): 0, ('Bar', 0): 0}
>>> for (k, j), v in list(d.items()): # list key-value pairs for safe iteration
...     del d[k,j] # remove the old key (and value)
...     d[(k.lower(), j)] = v # set the new key-value pair
... 
>>> d
{('foo', 0): 0, ('bar', 0): 0}

Note, in Python 2, dict.items() returns a list copy, so passing it to list is unnecessary there, but I chose to leave it for full compatibility with Python 3.

You can also use a generator statement fed to dict, and let the old dict get garbage collected. This is also compatible with Python 2.7, 2.6, and 3.

>>> d = {('Foo', 0): 0, ('Bar', 0): 0}
>>> d = dict(((k.lower(), j), v) for (k, j), v in d.items())
>>> d
{('bar', 0): 0, ('foo', 0): 0}

You can use a dict comprehension to build a new dict with your changes applied:

d = { (a.lower(), b) : v for (a,b), v in d.items() }
Answered By: Niklas B.

Tuples are "immutable", which means you cannot change a tuple in place after it is created. However, you can make a new tuple by modifying the existing tuple. I used the word "immutable" because that is the Pythonic word, better than "read only".

Lists are mutable. Interestingly enough, strings are immutable, but that rarely causes any problem.

Answered By: Joseph Schachner