0

假设我有这本字典:

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

如何引用键中的元素?例如,如果程序在键的第二个元素中找到字符“c”,我希望程序执行特定的行。

4

3 回答 3

2

您可以简单地遍历键并检查:

>>> 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
于 2013-11-12T12:13:31.173 回答
1

使用列表推导:

>>> 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]

对于键值对迭代 dict.iteritems

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

如果有多个这样的行,而您只有一个,则使用next

>>> next((dic[k] for k in dic if k[1]=='c'), None)
1
于 2013-11-12T12:13:45.767 回答
1

您可以通过遍历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
于 2013-11-12T12:22:47.450 回答