Posted By

chrisaiv on 09/02/09


Tagged

python


Versions (?)

Python: List + Dictionary Basics


 / Published in: Python
 

Here are a few examples on how to use Lists and Dictionaries in Python. It's by no means exhaustive, just a quick reference.

  1. #List Example
  2. pals = list()
  3. pals.append( "chris" )
  4. pals.append( "sandy" )
  5. pals.append( "josie" )
  6. print "Items in List => " + str(pals), "List Length => " + str(len(pals))
  7.  
  8. print "\n"
  9. #Dictionary Example: Great for placing key value pairs without knowing in advance what we will be putting in the dictionary
  10. pal = dict()
  11. pal['first'] = 'Chris'
  12. pal['last'] = 'Aiv'
  13. pal['email'] = '[email protected]'
  14. pal['phone'] = '555-555-5555'
  15. print pal
  16.  
  17. print "\n"
  18.  
  19. #Forgiving way to find an item within a dictionary
  20. print pal.get("age", "Age not available")
  21. print pal.get("phone", "Phone not available")
  22.  
  23. print "\n"
  24.  
  25. #Looping through a Dictionary
  26. print "~~KEY : Value~~"
  27. for key in pal:
  28. print key, ":", pal[key]
  29.  
  30. print "\n"
  31.  
  32. #Find out what capabilities are available in a particular Data Object
  33. print dir(pals)

Report this snippet  

You need to login to post a comment.