^^Python. dictionaries

 

  1. Built-in compound types: list tuple range set dict
  2. lib/4.10. Mapping Types — dict
  3. py/tutor/datastructures.html#dictionaries

  4. How many of you all learned to hash tables ?
    yt/Modern Dictionaries by Raymond Hettinger

Create a dict  (e' la prima cosa da saper fare)

all examples return the same dictionary

 
a = {'one': 1, 'two': 2, 'three': 3}

comma-separated list of  key: value  pairs, within braces


b = {'two': 2, 'three': 3, 'one': 1,}   # ordine non conta
c = dict(a)
d = dict(one=1, two=2, three=3)
e = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
f = dict([('one', 1), ('two', 2), ('three', 3)])
 
a == b == c == d == e == f
 True 

Create a void dict    a={}  or  a=dict()

 

list({'c':5,'a':2,'b':4})   ['c', 'a', 'b']

la lista di un dizionario e' la lista delle chiavi, i valori non sono considerati.

Per creare la lista dei valori

{'c':5,'a':2,'b':4}.values()    dict_values([5, 2, 4])

 

read/write(insert-update): by index, by key

same indexing syntax used for lists

 

nr['two']           # read value by key
                    # Raises a KeyError if key not in map.
nr['ten'] = 10      # Set a new key:value pair

vo:  r/w ≡  read/write  ≡   Items accessed and set

To avoid KeyError

class cnt(dict):
    def __missing__(self, key):
        return 0

crea il comportamento di collections.Counter([iterable-or-mapping])