字典
聲明字典
- 字典是容器類型,也是序列绩鸣。以鍵值對作為元素(key-value)。
- 鍵值對:
key:value
,鍵必須唯一且不可改變(數(shù)值纱兑、布爾呀闻、字符串和元組);通常使用字符串潜慎;若定義了相同的key時(shí)捡多,它會(huì)按照后一個(gè)出現(xiàn)的值為準(zhǔn)蓖康;值可以不唯一,可以是任何類型的數(shù)據(jù) - 使用
{ }
表示 - 字典是可變的(元素可變)
dict1 = {'hero':'lucian', 2:'oneplus', True:'True',(10,20):'坐標(biāo)(10,20)'}
print(dict1)
result:
{'hero': 'lucian', 2: 'oneplus', True: 'True', (10, 20): '坐標(biāo)(10,20)'}
獲取字典的元素對應(yīng)的值
- 字典存數(shù)據(jù)垒手,實(shí)質(zhì)存的value蒜焊,key是獲取value的手段
-
dict_name[key]
-- 通過key獲取值,若key不存在時(shí)返回KeyError
print(dict_list['name'],dict_list['medicine'])
result:
shiting wang yuting
-
dict_name.get(key)
-- 通過key獲取值,若key不存在返回None,代表沒有
print(dict_list.get('a'))
result:
None
注:key肯定存在時(shí)用[],可能不存在或不希望返回錯(cuò)誤時(shí)用get
字典遍歷
- 遍歷字典直接取到字典的key值
for k in person:
print(k,person[k])
for k,v in person.items():
print(k,v)
result:
name 某寶
age 10
boss 某云
sex 男
name 某寶
age 10
boss 某云
sex 男
修改元素
- 語法
dict_name[key] = value
person['sex'] = '女'
print(person)
增加元素
dict_name[new_key] = value
del person['age']
刪除元素
del dict_name[key]
a = person.pop('boss') #a保存的是刪除key對應(yīng)的value
字典相關(guān)計(jì)算
- 字典不支持 + 和 *
- in 和 not in -- 判斷key在字典中是否存在
-
len(dict_name)
獲取字典中元素的數(shù)量 -
dict_name.clear()
刪除字典中所有的元素 -
dict_name.copy()
復(fù)制字典中的鍵值對到新的字典科贬,屬于淺拷貝
computer1 = computers #復(fù)制computers的地址給computer1
computer2 = computers.copy() #復(fù)制computers的全部元素到一個(gè)新的內(nèi)存空間中泳梆,并且將新的地址給computer2
-
copy.deepcopy(dict_name)
需先導(dǎo)入copy
模塊,屬于深拷貝 -
dict.fromkeys(seq, Default = None)
將列表轉(zhuǎn)換字典,將序列seq中每個(gè)值作為key榜掌,默認(rèn)值為value創(chuàng)建一個(gè)新的字典.默認(rèn)值不寫時(shí)為None
print(dict.fromkeys(computers,12))
- 獲取字典項(xiàng)
# dict_name.keys() 獲取字典中的所有key优妙,返回dict_keys類型
print(type(computers.keys()),computers.keys())
# dict_name.values() 獲取字典中所有key對應(yīng)的value,返回dict_values類型
print(type(computers.values()),computers.values())
# dict_name.items() 獲取字典所有的元憎账,返回dict_items類型套硼。
print(type(computers.items()),computers.items())
# 不推薦使用,遍歷數(shù)據(jù)時(shí)會(huì)轉(zhuǎn)換數(shù)據(jù)胞皱,占用更大的資源邪意。
result:
<class 'dict_keys'> dict_keys(['brand', 'color'])
<class 'dict_values'> dict_values(['聯(lián)想', 'white'])
<class 'dict_items'> dict_items([('brand', '聯(lián)想'), ('color', 'white')])
-
dict_name.setdefault(key, Default=None)
給字典添加鍵值對,如果鍵值對存在,就不作處理
computers.setdefault('value','nice')
-
dict1.update(dict2)
將字典2的鍵值對更新到字典1中朴恳,如果字典2的鍵值對在字典1中存在,就更新對應(yīng)鍵的值
dict1 = {'age':10,'name':'007'}
dict2 = {'num':10,'name':'king'}
print('before updating: ',dict1)
dict1.update(dict2)
result:
{'brand': '聯(lián)想', 'color': 'white', 'value': 'nice'}
before updating: {'age': 10, 'name': '007'}
updated: {'age': 10, 'name': 'king', 'num': 10}
list和dict的組合
- 數(shù)據(jù)保存多個(gè)數(shù)據(jù)的類型是同一種類型允蚣,使用列表
保存多個(gè)學(xué)生的信息 students_info = [{}, {}, {}...] - 數(shù)據(jù)保存多個(gè)數(shù)據(jù)的類型不同于颖,使用字典
如保存
student_info = [
{'name':'lucian','age':10},
{'name':'lax','age':12},
{'name':'gaylun','age':14}
]
py_class = {
'class_name':'python1806',
'students':student_info,
'location':'2_classroom'
}
- 輸入一名學(xué)生的姓名,根據(jù)姓名刪除對應(yīng)的學(xué)生
name = input('輸入姓名:')
for item in py_class['students'][:]:
if item['name'] == name:
py_class['students'].remove(item)
print('已刪除' )
print(py_class)
集合set
集合在python中是一種無序的可變且值唯一的容器類型
- 聲明集合
set1 = {1,3,'a',(1,2),True}
print(set1,type(set1))
set2 = set('dongdongqiang')
print(set2)
# 將其他的序列轉(zhuǎn)換成集合嚷兔,自帶一個(gè)去重的功能
#定義空集合必須 set1 = set()
result:
{(1, 2), 1, 3, 'a'} <class 'set'>
{'g', 'q', 'n', 'o', 'i', 'd', 'a'}
- 集合不能單獨(dú)獲取其中的某一個(gè)元素的,只能通過遍歷獲取集合的元素
for item in set1:
print(item)
result:
(1, 2)
1
3
a
-
添加元素
set_name.add(obj)
set1.remove('old') print(set1) result: {(1, 2), 1, 3, 'goods', 'a'}
set1.update(set2)
set1.update({'new','old'}) print(set1) result: {(1, 2), 1, 'new', 3, 'goods', 'old', 'a'}
-
刪除元素
- set_name.remove(obj) 刪除集合中指定的元素
set1.remove('old') print(set1) result: {(1, 2), 1, 'new', 3, 'goods', 'a'}
- set_name.clear() 刪除整個(gè)集合的元素
- del set_name 刪除集合
-
集合中不能修改元素
-
數(shù)學(xué)相關(guān)運(yùn)算
# a.判斷包含情況
'''
集合1 >= 集合2 判斷集合2是集合1的子集
集合1 <= 集合2 判斷集合1是集合2的子集
'''
# b.求交并補(bǔ)
'''
并集:集合1 | 集合2 求兩個(gè)集合的全部部分
交集:集合1 & 交集2 求兩個(gè)集合公共部分
補(bǔ)集:集合1 ^ 集合2 求兩個(gè)集合除公共部分以外的部分
'''
# c.差集
'''
集合1 - 集合2 集合1對于集合2沒有的部分
'''