When a key is a tuple in a dictionary in Python

I am having trouble understanding this. I have a dictionary where the key is a tuple consisting of two lines. I want the bottom line of the first line in this tuple, is this possible?

+4
source share
4 answers

Since the tuple is immutable, you need to delete the old one and create a new one. This works in Python 2 and 3, and it retains 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 that in Python 2, dict.items () returns a copy of the list, so it does not need to be sent to the list, but I decided to leave it for full compatibility with Python 3.

, dict, dict . Python 2.7, 2.6 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}
+3

dict dict :

d = { (a.lower(), b) : v for (a,b), v in d.items() }
+4

You will need to change the string to lowercase before inserting it into the tuple. Tuples are read-only after they are created.

0
source

Sorry, you need to create a new key. Something like that:

>>> key, value = ('SPAM', 'eggs'), 'potato'
>>> d = {key: value}
>>> print d
{('SPAM', 'eggs'): 'potato'}
>>> new_key = (key[0].lower(),) + key[1:]
>>> d[new_key] = d.pop(key)
>>> print d
{('spam', 'eggs'): 'potato'}
0
source

Source: https://habr.com/ru/post/1527334/


All Articles