example | explanation / remarks |
---|---|
d = {} | construct an empty dictionary |
d = {“age”: 17, “school”: “Adam High School”, “transportation”: “bus”} | construct a dictionary with data |
d[“age”]=18 | add or change value of a key |
v = d[“age”] | get value associated with a key |
l = len(d) | get number of keys (which is the same as number of values) |
for key,val in d.items(): … | loop over all key,val pairs |
d.clear() | delete all entries |
d.copy() | returns a (shallow!) copy of the dictionary |
d.get(key, default=None) | returns a value associated with a key. if key not found → return default |
d.setdefault(key, default=None) | if key exist → do nothing. if not → add the specified key,default pair |
d.fromkeys(seq, value=None) | seq=list of keys. add these keys to the dictionary, all having same associated value=value |
d.has_key(key) | returns a boolean value: True if key exists, else → False |
d.keys() | returns a list of the keys: [key1, key2, …] |
d.values() | returns an iterable of the values |
d.items() | returns a list of tuples: [(key1,val1),(key2,val2),…] |
d.update(d2) | add all d2 key,value pairs to d |
del dict[“school”] | delete a key,value pair based on key |
type(d) | <class 'dict'> |
cmp(d1, d2) | compares two dictionaries [need more info!] |