Python: List + Dictionary Basics


/ Published in: Python
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.