I want to access a specific element of a tuple in a dictionary of tuples. Let's say that I have a dictionary with a unique key, and a tuple with three values, for each key. I want to write a iterator the prints every third item in a tuple for every element in the dictionary.
For example
dict = {"abc":(1,2,3), "bcd":(2,3,4), "cde", (3,4,5)}
for item in dict:
print item[2]
But this returns
c
d
e
Where am I going wrong?
To access the tuple elements from the dictionary and contains them in a list. We have to initialize a dictionary and pass the tuple key and value as an argument. Now to get all tuple keys from the dictionary we have to use the Python list comprehension method.
In the majority of programming languages when you need to access a nested data type (such as arrays, lists, or tuples), you append the brackets to get to the innermost item. The first bracket gives you the location of the tuple in your list. The second bracket gives you the location of the item in the tuple.
There are two ways to access a single value of a dictionary: The square brackets [] approach. The safer get() method.
for item in dict:
print dict[item][2]
Also, you should not name anything after a built-in, so name your dictionary 'd'
or something other than 'dict'
for item in dict:
does the same thing as for item in dict.keys()
.
Alternatively, you can do:
for item in dict.values():
print item[2]
Your code is close, but you must key into the dictionary and THEN print the value in index 2.
You are printing parts of the Keys. You want to print parts of the Values associated with those Keys:
for item in dict:
print dict[item][2]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With