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"]=
print(dic1)
(2)删除 del 删除
dic={"name":"sang","age":,"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":,"hobby":"game"}
print(dic)
dic.clear()
print(dic)
(3) ret return(返回)
dic1={"name":"sang"}
dic1["age"]=
print(dic1)
ret=dic1.setdefault("age",) 键存在,不改动,返回字典中相应的键对应的值
print(ret) ret2=dic1.setdefault("hobby","girl") 键不存在,在字典中中增加新的键值对,并返回相应的值
print(dic1)
print(ret2)
(4)查找
dic3={"name":"sang","age":,"hobby":"game"} # 查,通过键去查
print(dic3["name"])
print(list(dic3.keys()))
print(list(dic3.values()))
print(list(dic3.items()))
结果为:
(5)update 更新 修改,升级,更新档
dic4={"name":"sang","age":,"hobby":"cdf"}
dic5={"":"","":""}
dic5={"":"","name":""}
dic4.update(dic5)
print(dic4)
print(dic5)
(6)
dic={"name":"sang","age":,"hobby":"game"}
print(dic.pop('age')) #删除字典中指定键值对,并返回该键值对的值
ret=dic.pop('age')
print(ret)
print(dic)
(7)
dic={:"",:"",:""}
#print(sorted(dic.items())) 默认按键值来排序
# dic5={"name":"sang","age":}
# 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*)
结果:
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"[:]) 结果:
lloword
4.3 关键字in
print( in [,,])
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=''
b='abc'
d=''
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')) # 统计元素个数
结果: print(st.center(,'#')) # 居中
结果:###########hello kitty {name} is {age}############ print(st.startswith('he')) # 判断是否以某个内容开头
结果: True print(st.find('t'))
结果: print(st.format(name='alex',age=)) # 格式化输出的另一种方式 待定:?:{}
结果:
hello kitty alex is print('My tLtle'.lower()) # 把所有的大写变小写 print('My tLtle'.upper()) #把所有的小写变大写
结果:
my tltle
MY TLTLE print('\tMy tLtle\n'.strip()) 去除空格字符
结果:My tLtle print('My title title'.replace('itle','lesson',))
结果:My tlesson title print('My title title'.split('i',))
结果:
['My t', 'tle title'] 表示1次,