字典&集合

# 04 字典dict 和 集合set
# 創(chuàng)建字典的幾種方法
dic1 = {'name': 'bob', 'age': 22, 'gender': 'male'}
print(dic1['name'])

dic2 = dict({'name': 'bob', 'age': 22, 'gender': 'male'})
print(dic2['name'])

dic3 = dict([('name', 'bob'), ('age', 22), ('gender', 'male')])
print(dic3['age'])

dic4 = dict(name='bob', age=22, gender='male')
print(dic4['gender'])

print(dic1 == dic2 == dic3 == dic4) # true

# 創(chuàng)建集合
s1 = {1, 2, 'hello'}
s2 = set([1, 2, 'hello'])
print(s1 == s2)

# 訪問字典
dic1['name']
findDic = dic1.get('name', 'null')  # get(key,default),若不存在name的value值則返回null
findNotDic = dic1.get('bilibili', 'null')
print(findDic,findNotDic)

# 訪問集合
# 集合不支持索引操作,集合本質(zhì)上是一個(gè)哈希表
# 用value in dict/set來判斷一個(gè)元素是否在字典或集合內(nèi)
# print(s1[0]) #將會(huì)拋出異常
print(1 in s1)
print('name' in dic1)

# 字典增刪查改
dic1['subject'] = 'math'    # 增加
print(dic1)
dic1['name'] = 'lily'  # 更新key對(duì)應(yīng)的value值
print(dic1)
delDic1 = dic1.pop('name')  # 刪除name的key-value
print(dic1)

# 集合增刪查改,
# 集合中的pop()操作是刪除集合中最后一個(gè)元素,然而集合本身是無序的,不能確定會(huì)刪除掉哪個(gè)元素,所以謹(jǐn)慎使用
s1.add(45)  # 增加
print(s1)
s1.remove(1) # 刪除
print(s1)

# 排序,
# 根據(jù)字典的key進(jìn)行升序
dict10 = {'b': 70, 'a': 10, 'c': 45}
dict_sort_by_key = sorted(dict10.items(), key = lambda x : x[0])
print(dict_sort_by_key)
# 根據(jù)字典的value進(jìn)行升序
dict_sort_by_valve = sorted (dict10.items(),key = lambda x : x[1])
print(dict_sort_by_valve)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容