Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access specific element of dictionary of tuples

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?

like image 340
user1876508 Avatar asked Apr 02 '13 19:04

user1876508


People also ask

How do you access a dictionary within a tuple?

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.

How do you access elements in a list of tuples in Python?

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.

How do I find a specific value in a dictionary?

There are two ways to access a single value of a dictionary: The square brackets [] approach. The safer get() method.


Video Answer


2 Answers

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]
like image 129
Rushy Panchal Avatar answered Nov 10 '22 00:11

Rushy Panchal


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]
like image 24
jeffdt Avatar answered Nov 10 '22 00:11

jeffdt