Learning by doing: Reading books and trying to understand the (code) examples
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
1.8 KiB

  1. from collections import defaultdict
  2. stocks = {"GOOG": (613.30, 625.86, 610.50),
  3. "MSFT": (30.25, 30.70, 30.19)}
  4. # different possibilities to get values from the dictionary
  5. print("GOOG: {}".format(stocks["GOOG"]))
  6. print("RIM: {}".format(stocks.get("RIM", "NOT FOUND")))
  7. stocks.setdefault("RIM", (67.38, 68.48, 67.28))
  8. print("RIM: {}".format(stocks["RIM"]))
  9. for stock, values in stocks.items():
  10. print("{} last value is {}".format(stock, values[0]))
  11. random_keys = {}
  12. random_keys["astring"] = "somestring"
  13. random_keys[5] = "aninteger"
  14. random_keys[25.2] = "floats work too"
  15. random_keys[("abc", 123)] = "so do tuples"
  16. class AnObject(object):
  17. def __init__(self, avalue):
  18. self.avalue = avalue
  19. my_object = AnObject(14)
  20. random_keys[my_object] = "We can even store objects"
  21. my_object.avalue = 12
  22. try:
  23. random_keys[[1, 2, 3]] = "We can't store lists though"
  24. except:
  25. print("unable to store list \n")
  26. for key, value in random_keys.items():
  27. print("{} has value {}".format(key, value))
  28. if hasattr(key, "avalue"):
  29. print("{}.avalue ={}".format(key, key.avalue))
  30. def letter_frequency(sentence):
  31. frequencies = {}
  32. for letter in sentence:
  33. frequency = frequencies.setdefault(letter, 0)
  34. frequencies[letter] = frequency + 1
  35. return frequencies
  36. print(letter_frequency("Hello world, what's going on?"))
  37. # defaultdict using built-in function
  38. def letter_frequency_defdict(sentence):
  39. frequencies = defaultdict(int)
  40. for letter in sentence:
  41. frequencies[letter] += 1
  42. return frequencies
  43. print(letter_frequency_defdict("Hello world, what's going on?"))
  44. # defaultdict using self defined function
  45. num_items = 0
  46. def tuple_counter():
  47. global num_items
  48. num_items += 1
  49. return num_items, []
  50. d = defaultdict(tuple_counter)
  51. d['a'][1].append("hello")
  52. d['b'][1].append("world")
  53. print(d)