Search code examples
pythondictionarytupleslowercase

When the key is a tuple in dictionary in Python


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?


Solution

  • 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}