5

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?

user1876508
  • 12,864
  • 21
  • 68
  • 105
  • 1
    Just a reminder: dictionaries are unordered, so you've got no guarantee that you'd get 3,4,5 as opposed to 5,3,4. – DSM Apr 02 '13 at 19:47
  • Do you know of any tutorials that explain ordered dictionaries? – user1876508 Apr 02 '13 at 19:53
  • While there *is* `collections.OrderedDict`, which preserves insertion order (it's not a `sorteddict`), most of the time simply iterating over the sorted keys instead suffices (e.g. `for item in sorted(d): print d[2])`. I don't know of any tutorials offhand. – DSM Apr 02 '13 at 19:56

2 Answers2

7
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]
Rushy Panchal
  • 16,979
  • 16
  • 61
  • 94
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]
jeffdt
  • 66
  • 3