當前位置:首頁 » 編程語言 » pythondict添加key

pythondict添加key

發布時間: 2025-05-14 10:33:59

python中字典常用的方法有哪些,分別有什麼作用

寫法:字典序列[key] = 值 ***字典為可變類型

常用方法:
1、# 新增字典中的數據
dict1 = {'name':'huu','age':20,'gender':'男'}
dict1['id'] = 133
print(dict1)

2、# 修改字典中的數據
dict1['name'] = 'xiauaiguai'
print(dict1)
3、刪除字典或刪除字典中指定鍵值對
del()/del:

dict1 = {'name':'huanghu','age':30,'gender':'男'}

# del(dict1) 直接將字典刪除了,運行報錯

del dict1['name']
print(dict1)
# del dict1[names] 刪除不存在的key,運行報錯

4、清空字典
clear():
dict1.clear() # 清空字典
print(dict1)

5、查找
key值查找
如果當前查找的key存在則返回對應的值,否則則報錯
函數查找
get():如果當前查找的key不存在則返回第二個參數值(默認值),
如果省略第二個參數則返回 None
key()

dict1 = {'name':'huhu','age':20,'gender':'男'}

print(dict1['name']) # huhu
print(dict1['id']) # 報錯

# 1, get()查找

print(dict1.get('name')) # huanghu
print(dict1.get('id',133)) # 133--如果當前查找的key不存在則返回第二個參數值(默認值)
print(dict1.get('id')) # None--如果省略第二個參數則返回 None

# 2, keys() 查找字典中所有的key,返回可迭代對象
print(dict1.keys()) # dict_keys(['name', 'age', 'gender'])

# 3,values() 查找字典中所有的values,
print(dict1.values()) # dict_values(['huanghu', 30, '男'])

# 4, items() 查找字典中所有的鍵值對,返回可迭代對象,裡面的數據是元組,
元組數據1是字典中的key,元組數據2是字典key對應的值
print(dict1.items()) # dict_items([('name', 'huahu'), ('age', 20), ('gender', '男')])

② python dict 是否有key

是字典嗎,字典有key 的。

dict_fore={'he':'haha','text','html'}
foriindict_fore.key():
print(i)

這樣,列印出來的就是鍵了

result:

he

text

③ python字典如何添加字典

dictname[key]。get方法:dictname.get(key)。(1)如果存在key,就會返回相對應的值。(2)get如果取得是不存在的key,會返回none。

方法get為訪問字典項提供了寬松的環境。通常,如果你試圖訪問字典中沒有的項,將引發錯誤,而get直接返回None,或者可設置默認返回值。

創建字典dict={d:1,b:2,c:3}添加內容adict[a]=500a{d:1,b:2,c:3,a:500}『python的設計哲學是「優雅」、「明確」、「簡單」。

熱點內容
php獲取上一月 發布:2025-05-14 13:22:52 瀏覽:88
購買雲伺服器並搭建自己網站 發布:2025-05-14 13:20:31 瀏覽:687
sqlserver建立視圖 發布:2025-05-14 13:11:56 瀏覽:484
搭建httpsgit伺服器搭建 發布:2025-05-14 13:09:47 瀏覽:255
新電腦拿回來我該怎麼配置 發布:2025-05-14 13:09:45 瀏覽:240
視頻伺服器新建ftp用戶 發布:2025-05-14 13:03:09 瀏覽:225
php花生 發布:2025-05-14 12:54:30 瀏覽:550
java人才 發布:2025-05-14 12:29:10 瀏覽:649
如何打開軟密碼 發布:2025-05-14 12:28:55 瀏覽:427
七牛存儲待遇 發布:2025-05-14 12:27:20 瀏覽:422