字典python中的问题 [英] problem in dictionary python
问题描述
我制作了一个字典,然后将值和键分成列表,现在看起来像这样:
I made a dictionary, then split up the values and keys into lists and now its looks like this:
keys = [(4,5),(5,6),(4,8)......so on].
values = [('west',1),('south',1).......]
然后我像这样制作了新字典,
Then I made a new dictionary like in this way,
final = dict((k,v[0]) for k,v in zip(keys, values))
当我执行-print final时-输出是这种形式... {(4,5):west,(5,6):south,......so on}
When I execute -print final - output is in this form... {(4,5):west,(5,6):south,......so on}
现在我需要具有键(4,5)的值...它可以是任何键..
Now i need to have the value of key (4,5)...it can be any key..
q:2
win = gap.pop() - here gap is a stack
print win - the output is (1,1)
return final.get(win) -
但是当我返回时,它给了我一个错误,最后是我用键和值列表创建的目录
but when I do this return, it gives me an error and final is the directory that I have made with lists of keys and values
错误是:"W"
推荐答案
为我工作:
>>> final = {(4,5):"West", (5,6): "East"}
>>> print final
{(4, 5): 'West', (5, 6): 'East'}
>>> final[(4,5)]
'West'
您可能想尝试final.get((4,5))
.
或发布更多代码,也许您喜欢final
做些什么.如果您没有找回价值,则至少应该得到一个KeyError
:
Or post more code, maybe you do something fancy with final
. If you don't get a value back, you should at least get a KeyError
:
>>> final[(7,8)]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: (7, 8)
在这种情况下,您要么必须处理异常:
In this case you either have to handle the exception:
try:
final[(7,8)]
except KeyError:
print "Key not in dict."
或使用final.get((7,8), <default value>)
,如果找不到密钥,则返回<default value>
(如果未指定默认值,则返回None
).
or use final.get((7,8), <default value>)
which will return <default value>
if the key is not found (or None
if you don't specify a default value).
这篇关于字典python中的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!