[英]How to get a certain value of a certain key in dictionary?
G={(-1, 1): [(0, 1)],
(0, 0): [(1, 0), (0, 1)],
(0, 1): [(1, 1), (0, 2), (-1, 1), (0, 0)],
(0, 2): [(0, 1)],
(1, 0): [(2, 0), (1, 1), (0, 0)],
(1, 1): [(0, 1), (1, 0)],
(2, 0): [(1, 0)]}
I have this dictionary in python and i want to go through each value of a certain key.我在 python 中有这本字典,我想查看某个键的每个值。 For example i have the key: (0,0) I want to print each value seperately like this:
例如我有键: (0,0) 我想像这样单独打印每个值:
Output:输出:
value 0 : (1,0)
value 1 : (0,1)
and I have this code我有这个代码
key=(0,0)
for v in range (len(G[key])):
print ("value ", v, ":", G[(0,0)].get(v))
G[(0,0)].get(v) is wrong and i get a message: G[(0,0)].get(v)是错误的,我收到一条消息:
AttributeError: 'list' object has no attribute 'get'
AttributeError: 'list' 对象没有属性 'get'
Do you know what should i use instead?你知道我应该用什么代替吗?
enumerate will get you the index and value: enumerate 将为您提供索引和值:
key=(0,0)
for idx,v in enumerate(G[key]):
print ("value ", idx, ":", v)
you can use print
build-in function with param sep='\\n'
:您可以使用带有参数
sep='\\n'
print
内置函数:
print(*G[(0,0)], sep='\n')
output:输出:
(1, 0)
(0, 1)
or you can use:或者你可以使用:
print(*['value %s : %s' % t for t in enumerate(G[(0,0)])], sep='\n')
output:输出:
value 0 : (1, 0)
value 1 : (0, 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.