python字典与集合常用操作

字典操作

d = {}
if k in d:
if d.has_key(k):
# be sure k exists in dict d
d[k]

# not sure k exists in dict d
d.get(k, defval)
# be sure k exists in dict d
del d[k]
d.pop(k)

# not sure k exists in dict d
d.pop(k, defret)
for k in d.keys(): print(k)
for v in d.values(): print(v)
for k,v in d.items(): print(k, v)

集合操作

s = set()
s = set([3,4,6,8])
s = set('hello')
s = a | b
s = a & b
s = a - b
s = a ^ b
# insert single element
s.add(x)

# insert elements by list
s.update([3,2,4,9])
# be sure x exists in set
s.remove(x)

# not sure x exists in set
s.discard(x)
if x in s:
for i in s: print(i)
for i in sorted(s): print(i)
Table of Contents