Reputation: 1
I have a dictionary in this format:
my_dict = {"key1":["value1", "value2", "value3"]}
Is there an easy way to get key1's third value? I guess I could get the whole list of values and then split it up, but there must be a better way
Upvotes: 0
Views: 70
Reputation: 68
I prefer to use get
i.e. my_dict.get('key1')[2]
If you use my_dict['key1'][2]
, you will get a KeyError
if key1
is not present in my_dict
Example -
>>> d = {1:3,4:6}
>>> d.get(7) # No Error
>>> d[7]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 7
Upvotes: 0
Reputation: 19322
You can do a simple look up in the following ways -
my_dict['key1'][2]
#Output = 'value3'
OR (using dict.get)
my_dict.get('key1')[2]
#Output = 'value3'
OR (if you want 3rd element without specifying the key)
list(my_dict.values())[0][2]
#Output = 'value3'
OR (if you want last element without specifying the key)
list(my_dict.values())[0][-1]
#Output = 'value3'
Upvotes: 1
Reputation: 6181
my_dict['key1'][2]
You access the list in. the value like any other list
Upvotes: 0