Python Dictionary

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 entry
b['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 b
del 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 dictionary
dict.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 key
dict.items() #Returns a list of dict's (key, value) tuple pairs
dict.keys() #Returns list of dictionary dict's keys
dict.setdefault(key, default=None) #Similar to get(), but will set dict[key]=default if key is not already in dict
dict.update(dict2) #Adds dictionary dict2's key-values pairs to dict
dict.values() #Returns list of dictionary dict's values

  

posted @ 2017-01-17 10:48  KennyRom  阅读(249)  评论(0编辑  收藏  举报