str_2='字典的基本操作'
v13 = str_2.center(100,'-')
print(v13)
"""字典的value可以是任意值"""
"""字典的key的唯一的,不变的,列表,布尔值,字典不可以作为字典的key"""
"""字典是没有顺序的"""
info = {
"k1":"v1",
"2":"v2",
"k3":[
"hyj",
[],
(1,2,3),
22,
33,
{
"kk1":"vv1",
"kk2":"vv2",
"kk3":(11,22)
}
],
"k4":[1,2,3]
}
"""索引,字典的key就相当于列表的索引值"""
print(''20)
print("索引,字典的key就相当于列表的索引值")
v=info['k1']
print(v)
v1=info['k3'][5]['kk3'][0]
print(v1)
"""支持del删除"""
print(''20)
print("支持del删除")
del info['k1']
del info['k3'][5]['kk3']
print(info)
"""进行for循环"""
print(''20)
print("进行for循环")
for item in info:
print(item)
"""输出字典的key"""
print(''20)
print("输出字典的key")
for key in info.keys():
print(key)
"""输出字典的值"""
print(""20)
print("输出字典的值")
for value in info.values():
print(value)
"""同时输出字典的键与值"""
print(''20)
print("同时输出字典的键与值")
for k,v in info.items():
print(k,v)
"""字典的方法"""
"""清空字典"""
#print(''50)
info.clear()
print(info)
"""根据提供的序列生成字典的key,并统一设置字典的值"""
print(''50)
print("根据提供的序列生成字典的key,并统一设置字典的值")
v2=dict.fromkeys(['huang',123,(1,2)],1111)
print(v2)
"""根据字典的key获取值,当key不存在时,默认值为None,也可以指定一个默认值"""
print(''50)
print("根据字典的key获取值,当key不存在时,默认值为None,也可以指定一个默认值")
v3 = info.get('k3')
v4 = info.get('kkk3',5555)
print(v3)
print(v4)
"""删除 pop()"""
print(''50)
print("删除 pop()")
v5 = info.pop('k4')
print(info)
print(v5)
"""随机删除 popitem"""
print(''50)
print("随机删除 popitem")
v6 = info.popitem()
print(info)
print(v6)
"""设置值,如果字典中已存在,不进行设置,保留原来的键值对"""
"""如果字典中不存在,进行设置,并获取当前的值"""
print(''50)
print("设置值,如果字典中已存在,不进行设置,保留原来的键值对")
print("中不存在,进行设置,并获取当前的值")
v7 = info.setdefault('k5','44455')
v8 = info.setdefault('2',1111)
print(v7)
print(info)
print(v8)
"""更新字典,对原有的进行替换,若没有就增加"""
print(''50)
print("更新字典,对原有的进行替换,若没有就增加")
info.update({"2":"111111111",'k6':"huangyoujian"})
print(info)
"""更新字典还有另外一种写法"""
print(''50)
print("更新字典还有另外一种写法")
info.update(k1=8888,k2=7777,k3='jscjbjbscj')
print(info)
"""成员操作符"""
print(''50)
print('成员操作符')
v9 = "k1" in info
print(v9)
v10 = 'k1' not in info
print(v10)
v11 = 8888 in info.values() # 判断某个值在不在字典中
print(v11)
str_1='END'
v12=str_1.center(100,'-')
print(v12)
转载于:https://blog.51cto.com/14182174/2344642