Reputation: 29
Given a dictionary:
self.mapping = {} # key= IP, value = (mac,id,port)
Where the value is 3-tuple values. If I know the key, how do I get a specific element from the 3-tuple? For instance, I want to get id
that corresponds to given IP
.
Thank you.
Upvotes: 2
Views: 458
Reputation: 1520
You could use get()
method to properly unpack data from your dict in a pythonic way:
mac_addr, c_id, port = self.mapping.get('192.168.1.1', (None, None, None))
It avoids KeyError
exception to be raised in case current IP is not in your dict.
If you only want to extract id field:
_, c_id, _ = self.mapping.get('192.168.1.1', (None, None, None))
Upvotes: 1
Reputation: 21
Python dictionaries and tuples are referenced using bracket notation. Dictionary values are referenced using corresponding keys; items in a tuple are referenced by index, using zero-based numbering (i.e. the first item in a tuple has the index 0, the second 1, and so on).
In your case, you can reference dictionary values using IP address keys:
self.mapping['IP address']
You can reference tuple items using indices:
my_tuple[1]
By combining the two, you can reference a specific item in a dictionary value tuple. In your example, ID is the second value at index 1, so you would use:
self.mapping['IP address'][1]
Upvotes: 2
Reputation: 44926
First, you get that whole tuple:
self.mapping["192.168.1.1"]
Then you just get the second element:
self.mapping["192.168.1.1"][1]
Upvotes: 0
Reputation: 4687
You need to use basic python sequences indexing. According to your sample:
self.mapping['some IP'][1]
Check documentation out.
Upvotes: 0