1. basic
Dictionary is a special sequence.
b = {'name':'haha', 'age':12}#in a dictionary, we have key and value.#Key is immutable. Hence, key can be strings, numbers and tuples.
2. accessing values
b = {'name':'haha', 'age':12}b['name'] # haha
3. update
b = {'name':'haha', 'age':12}b['age'] = 8 #updating existing entryb['Country'] = 'China' #add a new pair to the dictionary
4. delete
b = {'name':'haha', 'age':12}del b['name'] #remove entry with key 'name'b.clear() #remove all entries in bdel b #delete entire dictionary
5. properties
Duplicate key is not allowed.
#If we have duplicate key, the last wins.b = {'name':'Ben', 'age':13, 'name':'Jack'}b['name']#Jack
6. Built-in function
cmp(dict1, dict2)len(dict1)str(dict1) #Produces a printable string representation of a dictionarydict.clear()dict.copy()dict.fromkeys(str[, value]) #str is a sequence of new keys, If we have values, they will be the new value of the keys. Otherwise it will be none.dict.get(key, default=None) #For Key key, return value or default if key not in dictionary.dict.has_key(key) #return True, if dictionary has keydict.items() #Returns a list of dict's (key, value) tuple pairsdict.keys() #Returns list of dictionary dict's keysdict.setdefault(key, default=None) #Similar to get(), but will set dict[key]=default if key is not already in dictdict.update(dict2) #Adds dictionary dict2's key-values pairs to dictdict.values() #Returns list of dictionary dict's values