paul@2 | 1 | def f(d): |
paul@2 | 2 | return d.keys() |
paul@2 | 3 | |
paul@288 | 4 | def g(d): |
paul@288 | 5 | for key, value in d.items(): |
paul@288 | 6 | return value |
paul@2 | 7 | |
paul@459 | 8 | d = {10 : "a", 20 : "b", "c" : 30, (1, 2) : "d"} |
paul@494 | 9 | print "# d:", |
paul@300 | 10 | print d |
paul@288 | 11 | print d[10] # a |
paul@288 | 12 | print d[20] # b |
paul@300 | 13 | print d["c"] # 30 |
paul@459 | 14 | print d[(1, 2)] # d |
paul@288 | 15 | try: |
paul@288 | 16 | print d[30] # should fail with an exception |
paul@288 | 17 | except KeyError, exc: |
paul@288 | 18 | print "d[30]: key not found", exc.key |
paul@473 | 19 | print d.get(30) # None |
paul@473 | 20 | print d.get(30, "c") # c |
paul@475 | 21 | print d.has_key(20) # True |
paul@475 | 22 | print d.has_key(30) # False |
paul@288 | 23 | |
paul@283 | 24 | l = f(d) |
paul@494 | 25 | print "# l:", |
paul@288 | 26 | print l |
paul@283 | 27 | print 10 in l # True |
paul@283 | 28 | print 20 in l # True |
paul@300 | 29 | print "c" in l # True |
paul@459 | 30 | print "d" in l # False |
paul@283 | 31 | print 30 in l # False |
paul@459 | 32 | print (1, 2) in l # True |
paul@283 | 33 | |
paul@283 | 34 | l = d.values() |
paul@494 | 35 | print "# l:", |
paul@288 | 36 | print l |
paul@283 | 37 | print "a" in l # True |
paul@283 | 38 | print "b" in l # True |
paul@459 | 39 | print "c" in l # False |
paul@459 | 40 | print "d" in l # True |
paul@300 | 41 | print 30 in l # True |
paul@459 | 42 | print (1, 2) in l # False |
paul@283 | 43 | |
paul@459 | 44 | v = g(d) # either "a" or "b" or 30 or "d" |
paul@494 | 45 | print "# v:", |
paul@288 | 46 | print v |
paul@459 | 47 | print v == "a" or v == "b" or v == 30 or v == "d" # True |
paul@459 | 48 | print v == 10 or v == 20 or v == "c" or v == (1, 2) # False |
paul@283 | 49 | |
paul@288 | 50 | l = d.items() |
paul@494 | 51 | print "# l:", |
paul@288 | 52 | print l |
paul@288 | 53 | print (10, "a") in l # True |
paul@300 | 54 | print ("c", 30) in l # True |
paul@459 | 55 | print ((1, 2), "d") in l # True |
paul@288 | 56 | print (10, "b") in l # False |
paul@459 | 57 | |
paul@459 | 58 | # Try to put a list key in a dictionary. |
paul@459 | 59 | |
paul@459 | 60 | try: |
paul@459 | 61 | d[[1, 2]] = "e" |
paul@459 | 62 | print d[[1, 2]] |
paul@459 | 63 | except TypeError: |
paul@459 | 64 | print "d[[1, 2]]: key not appropriate" |
paul@475 | 65 | |
paul@475 | 66 | # Attempt to remove items. |
paul@475 | 67 | |
paul@475 | 68 | del d[20] |
paul@475 | 69 | print d.has_key(20) # False |
paul@475 | 70 | try: |
paul@475 | 71 | del d[30] # should fail with an exception |
paul@475 | 72 | except KeyError, exc: |
paul@475 | 73 | print "del d[30]: key not found", exc.key |
paul@475 | 74 | |
paul@475 | 75 | # Clear the dictionary. |
paul@475 | 76 | |
paul@475 | 77 | d.clear() |
paul@475 | 78 | print d # {} |