Advertisement
Rapptz

Untitled

May 6th, 2013
342
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.04 KB | None | 0 0
  1. d = {"foo" : "bar", "spam" : "eggs"}
  2.  
  3. print "d has $(d.Count) items"
  4.  
  5. //add a new item:
  6. d["test"] = "new item"
  7.  
  8. print "d has ${d.Count} items"
  9.  
  10. //change an existing item
  11. d["foo"] = "barbar"
  12.  
  13. //print everything in the dictionary
  14. for item in d:  //item is of type System.Collections.DictionaryEntry
  15.     print item.Key, ":", item.Value
  16.  
  17. //an alternative way
  18. for key in d.Keys:
  19.     print key, "->", d[key]
  20.  
  21. if d.ContainsKey("foo"):
  22.     print "has key foo"
  23.  
  24. if d.ContainsValue("eggs"):
  25.     print "has value eggs"
  26.  
  27. //get the first key: (have to explicitly convert to an array)
  28. print "first key:", array(d.Keys)[0]
  29.  
  30. //print the first value
  31. print "first value:", array(d.Values)[0]
  32.  
  33. //convert hash to a jagged array like python's dictionary.items:
  34. items = array((item.Key, item.Value) for item in d)
  35. //(('spam', 'eggs'), ('foo', 'barbar'), ('test', 'new item'))
  36.  
  37.  
  38. //Remove an item:
  39. d.Remove("test")
  40.  
  41.  
  42. //Getting a default value if the key is not found:
  43. //This works because d["badkey"] will return null
  44. item = d["badkey"] or "default value"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement