Omid
Omid

Reputation: 2677

Referencing to elements of tuples when used as keys in a python dictionary

Let's say I have this dictionary:

dic = {('a','b'): 0, ('b','c'): 1, ('d','e'): 2}

How can I reference to the elements within the key? For example I want the program to execute a specific line if it finds the character 'c' in the second element of the key.

Upvotes: 0

Views: 62

Answers (3)

thefourtheye
thefourtheye

Reputation: 239693

You can unpack the first and second elements of all the keys by iterating over the keys()

dic = {('a','b'): 0, ('b','c'): 1, ('d','e'): 2}
for first, second in dic.keys():
    if second == 'c':
        # execute the line you want
        pass

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251196

Use a list comprehension:

>>> dic = {('a','b'): 0, ('b','c'): 1, ('d','e'): 2}
>>> lines =[dic[k] for k in dic if k[1]=='c']  #returns all matching items
>>> lines
[1]

For key-value pairs iterate over dict.iteritems:

>>> [(k, v) for k, v in dic.iteritems() if k[1]=='c']
[(('b', 'c'), 1)]

If there are multiple such lines and you just one then use next:

>>> next((dic[k] for k in dic if k[1]=='c'), None)
1

Upvotes: 1

Simeon Visser
Simeon Visser

Reputation: 122536

You can simply iterate over the keys and check for that:

>>> dic = {('a','b'): 0, ('b','c'): 1, ('d','e'): 2}
>>> for key, value in dic.items():
...     if key[1] == 'c':
...         print key, value # or do something else
...
('b', 'c') 1

Upvotes: 2

Related Questions