dictionary(字典): 字典对象 字典是一种key - value 的数据类型,使用就像我们上学用的字典,通过笔划、字母来查对应页的详细内容。
1. dic={"name":"sang","age":22,"hobby":"game"} $字典有2大特点:*(1)无序,(2)key键唯一
print(dic)
2. dictionary的创建 #2种方法
(1)dic={"name":"sang","age":22,"hobby":"game"} 直接创建
dic2=(dic)
print(dic2)
(2)dic3=dict((("name","sang"),)) 通过dict
print(dic3)
3. dictionary中的操作:
(1)增加
dic1={"name":"sang"} dic1["age"]=18 print(dic1)
(2)删除 del 删除
dic={"name":"sang","age":22,"hobby":"game"} print(dic) del (dic) print(dic)
del dic['name'] 删除字典中指定键值对
print(dic.pop('age')) #删除字典中指定键值对,并返回该键值对的值 ret=dic.pop('age') print(ret) print(dic)
clear 清空列表
dic={"name":"sang","age":22,"hobby":"game"} print(dic) dic.clear() print(dic)
(3) ret return(返回)
dic1={"name":"sang"} dic1["age"]=18 print(dic1) ret=dic1.setdefault("age",34) 键存在,不改动,返回字典中相应的键对应的值 print(ret) ret2=dic1.setdefault("hobby","girl") 键不存在,在字典中中增加新的键值对,并返回相应的值 print(dic1) print(ret2)
(4)查找
dic3={"name":"sang","age":22,"hobby":"game"} # 查,通过键去查 print(dic3["name"]) print(list(dic3.keys())) print(list(dic3.values())) print(list(dic3.items()))
结果为:
(5)update 更新 修改,升级,更新档
dic4={"name":"sang","age":22,"hobby":"cdf"} dic5={"1":"111","2":"222"} dic5={"1":"111","name":"222"} dic4.update(dic5) print(dic4) print(dic5)
(6)
dic={"name":"sang","age":22,"hobby":"game"}
print(dic.pop('age')) #删除字典中指定键值对,并返回该键值对的值 ret=dic.pop('age') print(ret) print(dic)
(7)
dic={5:"555",2:"666",4:"333"} #print(sorted(dic.items())) 默认按键值来排序 # dic5={"name":"sang","age":22} # for i in dic5: # print(i,dic5[i]) # for i,v in dic5.items(): 不推荐使用,占内存 # print(i,v)
4.String 的一些命令操作 :
4.1重复输出字符串
a="Hello World!" print(a) print(a*20)
结果:
Hello World!
Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello World!Hello
4.2 [] ,[:] 通过索引获取字符串中字符,这里和列表的切片操作是相同的,具体内容见列表
print("helloword"[2:]) 结果: lloword
4.3 关键字in
print(123 in [23,45,123]) print('e2l' in 'hello') 结果: True False
4.4 格式字符串
# % 格式字符串 print('alex is a good teacher') print('%s is a good teacher'%'alex') 结果: alex is a good teacher alex is a good teacher
4.5 字符串的连接
a='123' b='abc' d='44' c=a+b print(c) c= ''.join([a,b,d]) print(c) 结果: 123abc 123abc44
4.6 String的内置方法
st='hello kitty {name} is {age}' print(st.count('l')) # 统计元素个数 结果:2 print(st.center(50,'#')) # 居中 结果:###########hello kitty {name} is {age}############ print(st.startswith('he')) # 判断是否以某个内容开头 结果: True print(st.find('t')) 结果:8 print(st.format(name='alex',age=37)) # 格式化输出的另一种方式 待定:?:{} 结果: hello kitty alex is 37 print('My tLtle'.lower()) # 把所有的大写变小写 print('My tLtle'.upper()) #把所有的小写变大写 结果: my tltle MY TLTLE print(' My tLtle '.strip()) 去除空格字符 结果:My tLtle print('My title title'.replace('itle','lesson',1)) 结果:My tlesson title print('My title title'.split('i',1)) 结果: ['My t', 'tle title'] 1 表示1次,