简体   繁体   中英

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM