後浪小萌新Python 字典相關操作和方法

2021-10-08 15:13:24 字數 3820 閱讀 9280

字典不支援加法、乘法和比較大小的運算

舉例:

print(+

)print

(>

)

執行結果:

typeerror: unsupported operand type(s) for +: 'dict' and 'dict'

typeerror: '>' not supported between instances of 'dict' and 'dict'

判斷資料本身是否相等: ==,!=

print(==

)

true
is - 判斷兩個資料的位址是否相等

舉例:

a =

b =c = a

print

(a == b)

print

(a is b)

print

(a is c)

執行結果:

true

false

true

in 和 not in

key in 字典 - 判斷字典中是否有指定的key

舉例:

dict1 =

print(10

in dict1)

print

('b'

in dict1)

執行結果:

false

true

相關函式: len\dict

len(字典) - 獲取字典中鍵值對的個數

舉例:

dict1 =

print

(len

(dict1)

)

執行結果:

3
dict(資料) - 將其他資料轉換成字典(資料的要求:

序列序列中的元素還是序列

內部的序列有且只有兩個元素, 第乙個元素不可變)

舉例:

list1 =

['ab',(

10,20)

,['name'

,'張三']]

print

(dict

(list1)

)

執行結果:

將字典轉換成其他資料

將字典轉換成列表/元組 - 將字典的key作為列表/元組的元素

將字典轉換成字串

將字典轉換成布林

舉例:

stu =

# 1)將字典轉換成列表/元組 - 將字典的key作為列表/元組的元素

print

(list

(stu)

)print

(tuple

(stu)

)

# 2)將字典轉換成字串

print

(str

(stu)

) # 3

)將字典轉換成布林

print

(bool()

)print

(bool

(stu)

)

執行結果:

[

'name'

,'age'

,'score'](

'name'

,'age'

,'score'

)false

true

字典.clear()

舉例:

stu =

stu.

clear()

print

(stu)

執行結果:

字典.copy()

舉例:

stu =

stu2 = stu.

copy()

print

(stu2)

stu[

'name']=

'小花'

print

(stu2)

執行結果:

dict.fromkeys(序列, 預設值=none)

建立乙個新的字典,序列中所有的元素會作為新字典的key,預設值是所有key對應的值

舉例:

new_dict = dict.

fromkeys

('abc'

)print

(new_dict)

new_dict = dict.

fromkeys([

'name'

,'age'

,'***'],

0)print

(new_dict)

new_dict = dict.

fromkeys([

'name'

,'age'

,'***'],

['張三',19

,'男'])

print

(new_dict)

執行結果:

字典.items()、字典.keys()、字典.values()

舉例:

stu =

print

(stu.

items()

)print

(stu.

keys()

)print

(stu.

values()

)

執行結果:

dict_items([

('name'

,'小明'),

('age',18

),('score'

,100)]

)dict_keys([

'name'

,'age'

,'score'])

dict_values([

'小明',18

,100

])

字典.setdefault(key, value)

在字典中新增鍵值對(單純的新增鍵值對,不會修改)

舉例:

stu =

stu.

setdefault

('weight'

,100

)print

(stu)

stu.

setdefault

('name'

,'asd'

)print

(stu)

執行結果:

字典1.update(字典2)

將字典2中所有的鍵值對全部新增到字典1中

舉例:

stu.

update()

print

(stu)

執行結果:

後浪小萌新Python 列表相關操作

列表1 列表2 將列表1和列表2合併產生乙個新列表 舉例 list1 10 20,30 1 2,3 print list1 執行結果 10,20,30,1,2,3 列表 n n 列表 列表中的元素重複n次產生乙個新的列表 n是正整數 舉例 list2 10 20,30 3print list2 執行...

後浪小萌新Python 基礎語法

注釋就是 中說明性的文字,不參與程式的編譯執行 不影響程式的功能 單行注釋 在一行說明性文字前加 這是第一行注釋 這是第二行注釋 這是第三行注釋執行如下 多行注釋 將注釋內容寫在三個單引號或者三個雙引號之間 這是第一行注釋 這是第二行注釋 這是第三行注釋 注 為了防止轉譯,加了縮排,在python中...

後浪小萌新Python 列表基礎

注 列表是容器型資料型別,以 作為容器的標誌,裡面的多個元素用逗號隔開 元素1,元素2,元素3,列表是可變 指的是元素的個數 值和順序可變 列表是有序 列表的元素可以是任何型別資料 同乙個列表可以有多個型別不同的元素 注 容器型資料型別 乙個資料裡面同時儲存多個資料 list2 注 列表可以為空,有...