[英]Python/Pygame colours are no tuples: unhashable type error when used as dictionary keys
[英]Referencing to elements of tuples when used as keys in a python dictionary
假设我有这本字典:
dic = {('a','b'): 0, ('b','c'): 1, ('d','e'): 2}
如何引用密钥中的元素? 例如,如果程序在键的第二个元素中找到字符“ c”,我希望程序执行特定行。
您可以简单地遍历键并检查以下内容:
>>> 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
使用列表理解:
>>> 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
您可以通过遍历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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.