How to access only the key at the 0th or 1st position of the dictionary in python

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • CompUser7
    New Member
    • Sep 2010
    • 2

    How to access only the key at the 0th or 1st position of the dictionary in python

    Eg. Python{ 'Good' : '0', 'Bad' :'9', 'Lazy' : '7'}
    how do i access and print only 'Good' or 'Bad' or 'Lazy'
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Dictionary method keys().

    Code:
    >>> dd = { 'Good' : '0', 'Bad' :'9', 'Lazy' : '7'}
    >>> dd.keys()
    ['Bad', 'Good', 'Lazy']
    >>> dd.keys()[0]
    'Bad'
    >>>

    Comment

    • CompUser7
      New Member
      • Sep 2010
      • 2

      #3
      On top of that

      Hey thanks for the reply...
      But now I need to access the key names dynamically in a program. Eg.

      Code:
      a= raw_input (" which is the final attribute:")
      for i in python.items():
          if python.items()[i] == a:
              finalAttribute = python.items()[i]
      This giving me error saying
      Traceback (most recent call last):
      File "C:/Python27/test1.py", line 11, in <module>
      if somedict.items( )[i] == a:
      TypeError: list indices must be integers, not tuple
      Last edited by bvdet; Sep 15 '10, 08:09 PM. Reason: Add code tags. Please use code tags when posting code! [code].... your code goes here .... [/code]

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        Dictionary method items() returns a list of tuples.

        Comment

        Working...