py-day2-3 python 字典

# 字典的value可以是任何值
test = {'k1':'v1',
'k2':True,
'k3':[1,2,3,4,{'t1':'v2','t2':'v3'},5,6],
'k4':(88,99,66)
}
print(test) {'k1': 'v1', 'k2': True, 'k3': [1, 2, 3, 4, {'t1': 'v2', 't2': 'v3'}, 5, 6], 'k4': (88, 99, 66)}
# 布尔值(True=1,False=0)可以作为key但不能有重复。 列表,字典是不能作为字典的key
test = {
1:'abd',
'k1':'esd',
True: '',
(11,22):123,
[1,b,8]:'bes', 【列表,字典是不能作为字典的key】
  }
test = {
1:'abd',
'k1':'esd',
True: '',
}
print(test) {1: '', 'k1': 'esd'} test1 = {
'':'abd',
'k1':'esd',
True: '',
}
print(test1) {'': 'abd', 'k1': 'esd', True: ''}
#  字典是无序的
# 通过索引的方式找到指定元素。
test = {'k1':'v1',
'k2':True,
'k3':[1,2,3,4,{'t1':'v2','t2':(12,18)},5,6],
'k4':(88,99,66)
}
v = test['k3'][4]['t2'][0]
print(v) 12
#  字典支持del删除。
test = {'k1':'v1',
'k2':True,
'k3':[1,2,3,4,{'t1':'v2','t2':(12,18)},5,6],
'k4':(88,99,66)
}
del test['k3'][4]['t2']
del test['k4']
print(test) {'k1': 'v1', 'k2': True, 'k3': [1, 2, 3, 4, {'t1': 'v2'}, 5, 6]}
#  for循环默认循环的是key
test = {'k1':'v1',
'k2':True,
'k3':[1,2,3,4,{'t1':'v2','t2':(12,18)},5,6],
'k4':(88,99,66)
}
for item in test:
print(item) k1
k2
k3
k4
#  for循环加  .value()   循环键的值
test = {'k1':'v1',
'k2':True,
'k3':[1,2,3,4,{'t1':'v2','t2':(12,18)},5,6],
'k4':(88,99,66)
}
for item in test.values():
print(item) v1
True
[1, 2, 3, 4, {'t1': 'v2', 't2': (12, 18)}, 5, 6]
(88, 99, 66)
##  for循环  for k,v in 字典变量.items():    循环所有
test = {'k1':'v1',
'k2':True,
'k3':[1,2,3,4,{'t1':'v2','t2':(12,18)},5,6],
'k4':(88,99,66)
}
for k,v in test.items():
print(k,v) k1 v1
k2 True
k3 [1, 2, 3, 4, {'t1': 'v2', 't2': (12, 18)}, 5, 6]
k4 (88, 99, 66)
# dict.fromkeys([],)根据序列,创建字典,并指定统一的值
v = dict.fromkeys(['k1','k2','k3'],888)
print(v) {'k1': 888, 'k2': 888, 'k3': 888}
# dic.get() 根据key获取值,key不存在时,可以指定默认值(none)
dic ={'k1':'v1'}
v = dic.get('k1')
print(v) v1 dic ={'k1':'v1'}
v = dic.get('k8')
print(v) None
pop(),popitem() 删除并取值
dic ={'k1':'v1',
'k2':'v2',
'k3':'v3'
}
v = dic.pop('k1')
print(v)
print(dic) v1
{'k2': 'v2', 'k3': 'v3'} dic ={'k1':'v1',
'k2':'v2',
'k3':'v3'
}
v = dic.popitem()
print(v)
print(dic) ('k3', 'v3')
{'k1': 'v1', 'k2': 'v2'}
### setdefault() 设置值
# 已存在,不设置,获取当前key对应的值
dic ={'k1':'v1',
'k2':'v2',
'k3':'v3'
}
v = dic.setdefault('k1','')
print(v)
print(dic) v1
{'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
# 不存在,设置,获取当前key对应的值
dic ={'k1':'v1',
'k2':'v2',
'k3':'v3'
}
v = dic.setdefault('k6','')
print(v)
print(dic) 888
{'k1': 'v1', 'k2': 'v2', 'k3': 'v3', 'k6': ''}
# update()  字典更新   两种方法注意括号的使用
dic ={'k1':'v1',
'k2':'v2',
'k3':'v3'
}
v = dic.update({'k1':''}) 第一种
print(dic)
v1 = dic.update(k3=666) 第二种
print(dic) {'k1': '', 'k2': 'v2', 'k3': 'v3'}
{'k1': '', 'k2': 'v2', 'k3': 666}
上一篇:[转] 面向对象原则之GOF是招式,九大原则才是精髓


下一篇:Python 组合数据类型 集合