Python Forum
Best way to support multiple keys in dictionaries
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Best way to support multiple keys in dictionaries
#1
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'
>>>
Reply
#2
Lists aren't hashable, but tuples are. Try with a tuple.
Reply
#3
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#4
good work. It worked. I could not reproduce the problem using tuples. Thanks.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Create Dict from multiple Lists with duplicate Keys rhat398 10 4,056 Jun-26-2021, 11:12 AM
Last Post: Larz60+
  Get specific key from multiple keys in python dictionary pradeepkumarbe 0 2,113 Mar-24-2019, 07:23 PM
Last Post: pradeepkumarbe
  Working with dictionaries and keys netrate 9 5,819 Jun-01-2017, 05:29 AM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020