By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,907 Members | 1,932 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,907 IT Pros & Developers. It's quick & easy.

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

P: 2
Eg. Python{ 'Good' : '0', 'Bad' :'9', 'Lazy' : '7'}
how do i access and print only 'Good' or 'Bad' or 'Lazy'
Sep 15 '10 #1
Share this Question
Share on Google+
3 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
Dictionary method keys().

Expand|Select|Wrap|Line Numbers
  1. >>> dd = { 'Good' : '0', 'Bad' :'9', 'Lazy' : '7'}
  2. >>> dd.keys()
  3. ['Bad', 'Good', 'Lazy']
  4. >>> dd.keys()[0]
  5. 'Bad'
  6. >>> 
Sep 15 '10 #2

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

Expand|Select|Wrap|Line Numbers
  1. a= raw_input (" which is the final attribute:")
  2. for i in python.items():
  3.     if python.items()[i] == a:
  4.         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
Sep 15 '10 #3

bvdet
Expert Mod 2.5K+
P: 2,851
Dictionary method items() returns a list of tuples.
Sep 15 '10 #4

Post your reply

Sign in to post your reply or Sign up for a free account.