Python Dictionary and Set Methods
about Dictionary and Set that Python bulit-in types
Dictionary
-
methods
d.values() d.keys() d.items()
-
basic
key in d # if key in d, return True list(d) # return d keys d[key] = value # set d[key] to value d.pop(key[,default]) #if default set, when key not in dic, return default d.popitem() setdefault(key[,default]) #if key return value, else return default for k,v in d.items():
-
sort
#sorted by key sorted(dic.keys()[,reverse = False]) #return keys list sorted(dic.items()) #return items list #vsorted by lambda sorted(dic.items(), key = lambda x:x[1]) #sorted by key's length sorted(dic.items(), key = lamda x:len(x[0])
-
defaultdict
from collections import defaultdict dic = defaultdict(int) dic['a'] -> dic['a'] = 0
Set
-
methods
set.add(x) set.remove(x) set.discard(x) #remove method is if not in x , return ValueError
Leave a comment