setdefault方法:无则新建,有则跳过:
def word_cnt(mystring):
mystring=mystring.lower()
word_dict={}
for i in mystring:
if(i.isalpha()):
word_dict.setdefault(i,0)
word_dict[i]+=1
return word_dict
print(word_cnt("Hello World"))
get方法:没有key则返回默认设定。有则返回key
def my_func3():
word={'pig':1,'cat':2,'dog':3}
thisKey=word.get('elephant',0)
print(thisKey)
keys,values,items方法:返回键,值,键值对。
三个方法返回的不能被修改。
检查某物在字典的键/值:可以for循环:
def func4():
dict1={'name':'Tom','age':20}
if("name" in dict1.keys()):
print("1")
if("tom" in dict1.values()):
print("2");
添加键值对直接赋值,和列表不一样;乱序,无下标,所以不能切片
def func5():
dict1={'name':'Tom','age':20}
dict1["age"]=25