Python字典和集合

2021-10-08 19:43:34 字數 3165 閱讀 2595

特點:

# 建立有資料的字典

dict1 =

print

(type

(dict1)

)# 建立空字典

dict2 =

print

(type

(dict2)

)dict3 =

dict()

print

(type

(dict3)

)

字典序列[key]

= 值dict1 =

dict1[

"name"]=

"張飛"

print

(dict1)

# dict1[

"id"]=

110print

(dict1)

#

注意:

如果key存在,則修改這個key對應的值,如果key不存在,則新增此鍵值對

字典為可變型別

dict1 =

del dict1[

"name"

]# key不存在就會報錯

print

(dict1)

# del dict1

print

(dict1)

# 會報錯

字典序列[key]

= 值 # key存在就修改,不存在就新增

dict1 =

print

(dict1[

"name"])

# tom

print

(dict1[

"id"])

# 不存在,就報錯

注意:如果當前查詢的key存在,則返回對應的值,否則就報錯

字典序列.get(key, 預設值)
注意:如果當前查詢的key不存在則返回第二個引數(預設值),如果省略第二個引數,則返回none

dict1 =

print

(dict1.get(

"name"))

# tom

print

(dict1.get(

"id"

,110))

# 110

print

(dict1.get(

"id"))

# none

dict1 =

print

(dict1.keys())

# dict_keys(['name', 'age', 'gender'])

dict1 =

print

(dict1.values())

# dict_values(['tom', 18, '男'])

dict1 =

print

(dict1.items())

# dict_items([('name', 'tom'), ('age', 18), ('gender', '男')])

dict1 =

for key in dict1.keys():

print

(key)

dict1 =

for value in dict1.values():

print

(value)

dict1 =

for item in dict1.items():

print

(item)

dict1 =

for key, value in dict1.items():

print

(f" = "

)

建立集合使用{}或set,但是如果要建立空集合只能使用sert(),因為{}用來建立空字典

s1 =

print

(s1)

# 集合沒有順序,不支援下標操作

s2 =

print

(s2)

# s3 =

set(

"abcdefg"

)print

(s3)

# # 建立空集合

s4 =

set(

)print

(type

(s4))#

s5 =

print

(type

(s5)

)#

注意:1. 集合沒有順序,不支援下標操作

2. 集合可以去重

s1 =

s1.add(

100)

# 集合是可變型別

s1.add(

100)

# 集合的去重功能

s1.add([10

,20,30

])# 會報錯

s1.update([10

,20,30

])# 增加的資料是序列

s1.update(

100)

# 會報錯

注意:因為集合有去重功能,所以,當向集合內追加的資料是當前集合已有的資料,則不進行任何操作。

s1 =

s1.remove(10)

# s1.remove(10)

# 報錯

s1 =

print

(s1.pop())

print

(s1.pop(

))

s1 =

print(10

in s1)

# true

print(10

notin s1)

# false

Python字典和集合

判斷字典的元素 使用in 或者not in 和has key 函式來判斷 dict one in dict true dict.has key one true one notin dict false更新字典 dict one 11 dict three 33 dict 刪除字典和字典元素 dic...

Python之集合和字典

集合是乙個無重複元素的集,支援交,差,與等數 算,大括號和set 均能建立集合,但建立空集合只能用set 用於建立空字典 ab 建立集合 ab a set python 建立集合 b set cool a b o in a 判斷o是否在集合中 true a b a有而b沒有的元素 a b 存在於a或...

python 集合 字典

1.集合 建立 set 注意 建立空的集合要用set 特點 元素唯一,無序 運算 交集 並集 差集 方法 s.add x 新增單個元素 s.update 新增多個元素 s.remove 移除元素 s.clear 清空集合2.字典 建立 大括號建立字典的鍵時要加引號 dict key value 括號...