With an array x=['A','B','C']
, I can obtain several elements from it by just stating the index: eg.print(x[0:2])
yields ['A','B']
.
Now for a similar (ordered) dictionary x={1:'A', 2:'B', 3:'C'}
, how would I obtain 'A' and 'B' in the same way, by referencing the keys 1 and 2? Trying a method similar to the array above gives me an error:
TypeError: unhashable type: 'slice'
Note that the key tied to the entries are important, so it won't help converting the dictionary into a list.
Also, I plan on doing this to a lot of entries (>100), so calling each individual one won't be useful. My real program will involve numbered keys starting from 100 and calling keys 200 to 300, for example.
The way to retrieve a value from a dictionary is dict_name[key]
:
print x[1], x[2]
>> 'A', 'B'
Note that if the key doesn't exist this will raise a KeyError
. A way around it is to use get(key, default_value)
:
print x[9]
>> KeyError
print x.get(9, None)
>> None
You can use a for
loop in order to check multiple keys:
for potential_key in range(10):
print x[potential_key]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments