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
Solution 1:
Works for me:
>>> final = {(4,5):"West", (5,6): "East"}
>>> print final
{(4, 5): 'West', (5, 6): 'East'}
>>> final[(4,5)]
'West'
You might want to try final.get((4,5))
.
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."
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).
Solution 2:
Works for me:
>>> keys=[(4,5),(5,6)]
>>> values = ["west","south"]
>>> f=dict(zip(keys,values))
>>> f
{(4, 5): 'west', (5, 6): 'south'}
>>> f[(4,5)]
'west'
Post a Comment for "Problem In Dictionary Python"