python字典

python字典

python字典

字典是一种key-value的数据类型。 创建字典

students={
'stu1':'zw',
'stu2':'zgh',
'stu3':'yxl'
}

字典特点

  1. dict是无序的
  2. key必须是唯一的,本身可以去重
增加
students['stu4']="wl"
#输出{'stu1': 'zw', 'stu2': 'zgh', 'stu3': 'yxl', 'stu4': 'wl'}
修改
students['stu1']='sb'
#输出:{'stu1': 'sb', 'stu2': 'zgh', 'stu3': 'yxl', 'stu4': 'wl'}
删除
students.pop('stu1')
#输出:{'stu2': 'zgh', 'stu3': 'yxl', 'stu4': 'wl'}

del students['stu2']

输出:

students={
'stu1':'zw',
'stu2':'zgh',
'stu3':'yxl',
'stu4':'wl',
'stu5':'cyt',
'stu6':'zs'
}

随机删除(因为字典里的元素是无序的,所以删除是无序的):

students.popitem()

输出:

查找:
print('stu1' in students)#先查找,看是否存在这个key
print(students.get('stu1'))#再查询出来
#输出:True zw 
#另一种方法
print(students['stu1'])#如果查询的key不存在,会报错
多级字典嵌套:
其他方法:
students.values()
#输出dict_values(['zw', 'zgh', 'yxl', 'wl', 'cyt', 'zs'])
students.keys()
#输出:dict_keys(['stu1', 'stu2', 'stu3', 'stu4', 'stu5', 'stu6'])
students.setdefault('stu7','lcl')
#setdefault() 函数和get() 方法类似, 如果键不存在于字典中,将会添加键并将值设为默认值。

b={1:2,3:4,"stu1":'wyh'}
students.update(b)
print(students)

输出

students.items()

输出:dict_items([('stu1', 'zw'), ('stu2', 'zgh'), ('stu3', 'yxl'), ('stu4', 'wl'), ('stu5', 'cyt'), ('stu6', 'zs')])

循环dict:
for key in students:
    print(key,students[key])
#输出:
    stu1 zw
    stu2 zgh
    stu3 yxl
    stu4 wl
    stu5 cyt
    stu6 zs

for k,v in students.items():
print(k,v)

输出:

stu1 zw
stu2 zgh
stu3 yxl
stu4 wl
stu5 cyt
stu6 zs

集合操作:

集合是一个无序的,不重复的数据组合:

集合特点:

  1. 去重,把一个列表变成集合,就自动去重了
  2. 关系测试,测试两组数据之前的交集,差集,并集等关系

新建集合:

s=set([3,4,9,10]) #创建一个数值集合
t=set("Hello") #创建一个唯一字符的集合
print(s)#输出{9, 10, 3, 5}
print(t)#输出{'l', 'o', 'h', 'e'}

并集

a=t|s
print(a)#输出{3, 5, 9, 10, 'e', 'o', 'h', 'l'}

交集

a=t&s
print(a)#输出空的set()
t=set([2,3,4,5,6])
a=t&s
print(a)#输出{3, 5}

差集

a=s-t
print(a)#输出{9, 10}

对称差集

a=s^t
print(a) #输出{2, 4, 6, 9, 10}

基本操作

t.add('x')
print(t)#输出{2, 3, 4, 5, 6, 'x'}
s.update([10,37,42])#添加多项
print(s)#输出{3, 37, 5, 9, 10, 42}

使用remove()可以删除一项:

t.remove('h')
print(t)#输出{'l', 'e', 'o'},如果删除的数据在集合里没有,那么会报错

集合长度:

print(len(s))#输出4

测试x是否是s的成员:

print(3 in s )#输出True
print(3 not in s)#输出Flase
s.issubset(t)#测试s中的每一个元素都在t中
s<=t
s.issuperset(t)#测试t中的每一个元素都在s中
s.union(t)#返回一个新的set包含s和t中的每一个元素
s|t
s.intersection(t)#返回一个新的set包含s和t中的公共元素
s&t
s.difference(t)#返回一个新的set包含s中但是t中没有元素
s-t
s.symmetric_difference(t)#返回一个新的set包含s和t中不重复的元素
s^t
s.copy()#返回set “s”的一个浅复制
posted @ 2017-06-11 11:17  Doctor_Bool  阅读(179)  评论(0编辑  收藏  举报