how to add new tuple as key in dictionary?

Peter Otten __peter__ at web.de
Fri Jun 30 07:02:04 EDT 2017


Ho Yeung Lee wrote:

> I find that list can not be key in dictionary
> then find tuple can be as key
> 
> but when I add new tuple as key , got error in python 2.7
> 
> groupkey = {(0,0): []}
> groupkey[tuple([0,3])] = groupkey[tuple([0,3])] + [[0,1]]

First try to understand that you get the same error with every non-existent 
key:

>>> groupkey = {0: []}
>>> groupkey[1] = groupkey[1] + [2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 1

Second, it looks like you want to change a list as the value, assuming the 
empty list for non-existent keys. The straight-forward way to do this is:

>>> pairs = [
... ((0, 0), "foo"),
... ((0, 1), "bar"),
... ((0, 0), "baz"),
... ]
>>> groups = {}
>>> for k, v in pairs:
...     if k in groups:
...         groups[k].append(v)
...     else:
...         groups[k] = [v]
... 
>>> groups
{(0, 1): ['bar'], (0, 0): ['foo', 'baz']}

You can simplify this with the setdefault() method which in the example 
below will add an empty list for non-existent keys:

>>> groups = {}
>>> for k, v in pairs: groups.setdefault(k, []).append(v)
... 
>>> groups
{(0, 1): ['bar'], (0, 0): ['foo', 'baz']}


Finally there's a dedicated class for your use case:

>>> from collections import defaultdict
>>> groups = defaultdict(list)
>>> for k, v in pairs:
...     groups[k].append(v)
... 
>>> groups
defaultdict(<class 'list'>, {(0, 1): ['bar'], (0, 0): ['foo', 'baz']})

Missing entries spring into existence automatically -- defaultdict creates 
the value by calling the function (list in this case) passed to the 
constructor.




More information about the Python-list mailing list