Python Forum

Full Version: Best way to support multiple keys in dictionaries
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, imagine I have this situation:

>>> ip1 = "1.1.1.1"
>>> ip2 = "2.2.2.2"
>>> ip3 = "3.3.3.3"
>>>
>>> elements = {ip1+','+ip2:'100'}
>>> elements = {ip1+','+ip3:'200'}
Question:
Is this the best way to create a dictionary with two values in the key field? In this case I have IP1 and IP2 which are components of my key.
Is this a good approach? I attempted to use a tuple or list as a key value, but it seems that is not possible.

>>>
>>> l = [ip1,ip2]
>>> elements = {l:'100'}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>>
Lists aren't hashable, but tuples are. Try with a tuple.
You can use a tuple, and that is generally best. Tuples are built to be hashable, so they can be keys in dictionaries. As in elements = {(ip1, ip2): '100'}.

If you are getting an error with tuples, please show the code and the full text of the error.
good work. It worked. I could not reproduce the problem using tuples. Thanks.