在python字典中用作键时引用元组元素

时间:2013-11-12 12:12:06

标签: python dictionary key

假设我有这本词典:

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

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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