python字典update
㈠ 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-字典
1、字典:
兩大特點:無序,鍵唯一
無序存儲,鍵值對的形式存儲數據
鍵是唯一不可修改的,不能用列表做鍵
2、python中不可變類型:整形,字元串,元組
可變類型:字渣猜典,列表
3、字典中方法:
增加:
dic1 = {'name':'alex'}
dic1 = ['age'] =18
*dic1 = {'age':18,'name':'alex'}
dic1.setdefault() 鍵存在,不改動,返回字典相應鍵對應的值,鍵不存在,在字典中增加新的鍵值對,並返回相應的值
查找:
通過鍵查找
dic1.keys()列印字典中所有鍵
#dict1.keys['name','age'] --轉換成列表:list(dic1.keys())
dic1.values()列印字典中所有值
dic1.items()列印所有鍵值對
修改:
直接賦值
dic3= {'name':'alex','啟液age':18}
dic4 = {'sex':'male','age':36}
dic3.update(dic4) #有相同的key,值會修改
刪除:
dic.clear() #清空字典
del dic['name'] #刪除字典中指定鍵值對
dic.pop('age')#刪除字典中指定鍵值對,並返回該鍵值對的值
dic.popitem() #隨機刪除鍵值對,並以元組方式返回
其他操作涉及的方法:
dic1 =dict.formkeys(['host1','host2'],'test')#{'host1':'test','host2':'test'}
dic1 =dict.formkeys(['host1','host2','host3'],['test1','test2'])#{'host1':['test1','test2'],'host2':['test1','test2'],'host3':['test1','test2']}
dic1['host2'][1] = 'test3' #{'host3':['test1''test3'],'host2':['test1''test3'],'host1':['test1''test3']}
字典的嵌套:
字典的排序:
字典的遍歷:
字元串的操作
a = '123'
b= 'abc'
c = a+b #123abc
c='****'.join([a,b])#123****abc
st = 'hello kitty{name} is {age}'
st.count('l') #2 統計元素個數
st.captialize() #Hello kitty 首字母大寫
st.center(50,'-')#--------hello kitty --------居中
st.endswith('tty3')#判斷是否以某個內容結尾
st.startswith('he')#判斷是否以某個內容開頭
st.find('t') #8 查找第一個元素,並返回索引,不存在是返回-1
如旁型 st.format(name = 'alex',age= 37)#hello kitty alex is 37
st.format_map({'name' :'alex','age':27})#hello kitty alex is 27
st.index('t') #8 返回索引,找不到報錯
『ab'.isalnum()
'123'.isdigit()
㈢ Python 字典(dic)操作
具體函數有 set(),pop(),update(),items(),keys(),values(),get(),setdefault()
python 字典操作
假設字典為 dics = {0:'a', 1:'b', 'c':3}
二是使用dict本身提供的一個 get 方法,在Key不存在的時候,返回None:
>>> print dics.get('a')
0
>>> print dics.get('Paul')
None
dict.get(key,default=None) 兩個選項 一個 key 一個 default= None ----default可以是任何strings(字元)
2.從字典中取值,若找到則刪除;當鍵不存在時,顯示異常key error
[方法] dics.pop('key')
3.給字典添加一個條目。如果不存在,就指定特定的值;若存在,就算了。
[方法] dic.setdefault(key, value)
4. update
>>> a = {'a':1,'b':2}
>>> a.update({'c':3})
>>>a
{'a': 1,'c': 3,'b': 2}
>>> a.update({'c':4})
>>>a
{'a': 1,'c': 4,'b': 2}
dict的作用是建立一組 key 和一組 value 的映射關系,dict的key是不能重復的。
有的時候,我們只想要 dict 的 key,不關心 key 對應的 value,目的就是保證這個集合的元素不會重復,這時,set就派上用場了。
㈣ Python字典中幾個常用函數總結
1、get() 返回指定鍵的值,如果值不在字典中返回default值。
語法:dict.get(key,default=None)
參數:
key 字典中要查找的鍵。
default 如果指定鍵的值不存在時,返回該默認值值。
例:
dict={'Name':'alex','Age':21}
print("Name is:%s"% dict.get('Name')+"\n"+ "Age is:%d"% dict.get('Age'))
顯示結果為:
Name is:alex
Age is:21
2、update() 將一個字典中的值更新到另一個字典中。
語法:dict.update(dict2)
參數:
dict2 添加到指定字典dict里的字典。
例:
dict={'Name':'alex','Age':21}
dict2={'Sex':'female'}
dict.update(dict2)
print("Value is %s" % dict)
顯示結果為:
Value is {'Name': 'alex', 'Age': 21, 'Sex': 'female'}
㈤ python怎麼取字典第一個value
1、首先打開python編輯器,寫上注釋內容,如下圖所示。
㈥ python中,如何將多個字典組合成一個字典
Python編程將多個字典文件合並成一個字典文件,代碼如下:
//例子:合並a.txt和b.txt兩個字典文件
defreadf(filename):
lines=file(filename).readlines()
dic={}
foriinlines:
i_=i.split()
dic[i_[0]]=int(i_[1])
returndic
dica=readf('a.txt')
dicb=readf('b.txt')
lines=[]
foriindica:
percent=str(float(dicb[i])*100/dica[i])+'%'
s=''.join([i,str(dica[i]),str(dicb[i]),percent])
s+=' '
lines.append(s)
//合並成一個字典文件c.txt
withopen('c.txt','w')asf:
f.writelines(lines)
f.close()
㈦ python字典操作函數
字典是一種通過名字或者關鍵字引用的得數據結構,其鍵可以是數字、字元串、元組,這種結構類型也稱之為映射。字典類型是Python中唯一內建的映射類型,基本的操作包括如下:
(1)len():返回字典中鍵—值對的數量;
(2)d[k]:返回關鍵字對於的值;
(3)d[k]=v:將值關聯到鍵值k上;
(4)del d[k]:刪除鍵值為k的項;
(5)key in d:鍵值key是否在d中,是返回True,否則返回False。
(6)clear函數:清除字典中的所有項
(7)函數:返回一個具有相同鍵值的新字典;deep()函數使用深復制,復制其包含所有的值,這個方法可以解決由於副本修改而使原始字典也變化的問題
(8)fromkeys函數:使用給定的鍵建立新的字典,鍵默認對應的值為None
(9)get函數:訪問字典成員
(10)has_key函數:檢查字典中是否含有給出的鍵
(11)items和iteritems函數:items將所有的字典項以列表方式返回,列表中項來自(鍵,值),iteritems與items作用相似,但是返回的是一個迭代器對象而不是列表
(12)keys和iterkeys:keys將字典中的鍵以列表形式返回,iterkeys返回鍵的迭代器
(13)pop函數:刪除字典中對應的鍵
(14)popitem函數:移出字典中的項
(15)setdefault函數:類似於get方法,獲取與給定鍵相關聯的值,也可以在字典中不包含給定鍵的情況下設定相應的鍵值
(16)update函數:用一個字典更新另外一個字典
(17) values和itervalues函數:values以列表的形式返回字典中的值,itervalues返回值得迭代器,由於在字典中值不是唯一的,所以列表中可以包含重復的元素
一、字典的創建
1.1 直接創建字典
d={'one':1,'two':2,'three':3}
printd
printd['two']
printd['three']
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':3,'two':2,'one':1}
>>>
1.2 通過dict創建字典
# _*_ coding:utf-8 _*_
items=[('one',1),('two',2),('three',3),('four',4)]
printu'items中的內容:'
printitems
printu'利用dict創建字典,輸出字典內容:'
d=dict(items)
printd
printu'查詢字典中的內容:'
printd['one']
printd['three']
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
items中的內容:
[('one',1), ('two',2), ('three',3), ('four',4)]
利用dict創建字典,輸出字典內容:
{'four':4,'three':3,'two':2,'one':1}
查詢字典中的內容:
>>>
或者通過關鍵字創建字典
# _*_ coding:utf-8 _*_
d=dict(one=1,two=2,three=3)
printu'輸出字典內容:'
printd
printu'查詢字典中的內容:'
printd['one']
printd['three']
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
輸出字典內容:
{'three':3,'two':2,'one':1}
查詢字典中的內容:
>>>
二、字典的格式化字元串
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3,'four':4}
printd
print"three is %(three)s."%d
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'four':4,'three':3,'two':2,'one':1}
threeis3.
>>>
三、字典方法
3.1 clear函數:清除字典中的所有項
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3,'four':4}
printd
d.clear()
printd
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'four':4,'three':3,'two':2,'one':1}
{}
>>>
請看下面兩個例子
3.1.1
# _*_ coding:utf-8 _*_
d={}
dd=d
d['one']=1
d['two']=2
printdd
d={}
printd
printdd
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'two':2,'one':1}
{}
{'two':2,'one':1}
>>>
3.1.2
# _*_ coding:utf-8 _*_
d={}
dd=d
d['one']=1
d['two']=2
printdd
d.clear()
printd
printdd
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'two':2,'one':1}
{}
{}
>>>
3.1.2與3.1.1唯一不同的是在對字典d的清空處理上,3.1.1將d關聯到一個新的空字典上,這種方式對字典dd是沒有影響的,所以在字典d被置空後,字典dd裡面的值仍舊沒有變化。但是在3.1.2中clear方法清空字典d中的內容,clear是一個原地操作的方法,使得d中的內容全部被置空,這樣dd所指向的空間也被置空。
3.2 函數:返回一個具有相同鍵值的新字典
# _*_ coding:utf-8 _*_
x={'one':1,'two':2,'three':3,'test':['a','b','c']}
printu'初始X字典:'
printx
printu'X復制到Y:'
y=x.()
printu'Y字典:'
printy
y['three']=33
printu'修改Y中的值,觀察輸出:'
printy
printx
printu'刪除Y中的值,觀察輸出'
y['test'].remove('c')
printy
printx
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
初始X字典:
{'test': ['a','b','c'],'three':3,'two':2,'one':1}
X復制到Y:
Y字典:
{'test': ['a','b','c'],'one':1,'three':3,'two':2}
修改Y中的值,觀察輸出:
{'test': ['a','b','c'],'one':1,'three':33,'two':2}
{'test': ['a','b','c'],'three':3,'two':2,'one':1}
刪除Y中的值,觀察輸出
{'test': ['a','b'],'one':1,'three':33,'two':2}
{'test': ['a','b'],'three':3,'two':2,'one':1}
>>>
註:在復制的副本中對值進行替換後,對原來的字典不產生影響,但是如果修改了副本,原始的字典也會被修改。deep函數使用深復制,復制其包含所有的值,這個方法可以解決由於副本修改而使原始字典也變化的問題。
# _*_ coding:utf-8 _*_
fromimportdeep
x={}
x['test']=['a','b','c','d']
y=x.()
z=deep(x)
printu'輸出:'
printy
printz
printu'修改後輸出:'
x['test'].append('e')
printy
printz
運算輸出:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
輸出:
{'test': ['a','b','c','d']}
{'test': ['a','b','c','d']}
修改後輸出:
{'test': ['a','b','c','d','e']}
{'test': ['a','b','c','d']}
>>>
3.3 fromkeys函數:使用給定的鍵建立新的字典,鍵默認對應的值為None
# _*_ coding:utf-8 _*_
d=dict.fromkeys(['one','two','three'])
printd
運算輸出:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':None,'two':None,'one':None}
>>>
或者指定默認的對應值
# _*_ coding:utf-8 _*_
d=dict.fromkeys(['one','two','three'],'unknow')
printd
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':'unknow','two':'unknow','one':'unknow'}
>>>
3.4 get函數:訪問字典成員
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
printd
printd.get('one')
printd.get('four')
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':3,'two':2,'one':1}
1
None
>>>
註:get函數可以訪問字典中不存在的鍵,當該鍵不存在是返回None
3.5 has_key函數:檢查字典中是否含有給出的鍵
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
printd
printd.has_key('one')
printd.has_key('four')
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':3,'two':2,'one':1}
True
False
>>>
3.6 items和iteritems函數:items將所有的字典項以列表方式返回,列表中項來自(鍵,值),iteritems與items作用相似,但是返回的是一個迭代器對象而不是列表
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
printd
list=d.items()
forkey,valueinlist:
printkey,':',value
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':3,'two':2,'one':1}
three :3
two :2
one :1
>>>
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
printd
it=d.iteritems()
fork,vinit:
print"d[%s]="%k,v
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':3,'two':2,'one':1}
d[three]=3
d[two]=2
d[one]=1
>>>
3.7 keys和iterkeys:keys將字典中的鍵以列表形式返回,iterkeys返回鍵的迭代器
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
printd
printu'keys方法:'
list=d.keys()
printlist
printu'\niterkeys方法:'
it=d.iterkeys()
forxinit:
printx
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':3,'two':2,'one':1}
keys方法:
['three','two','one']
iterkeys方法:
three
two
one
>>>
3.8 pop函數:刪除字典中對應的鍵
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
printd
d.pop('one')
printd
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':3,'two':2,'one':1}
{'three':3,'two':2}
>>>
3.9 popitem函數:移出字典中的項
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
printd
d.popitem()
printd
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':3,'two':2,'one':1}
{'two':2,'one':1}
>>>
3.10 setdefault函數:類似於get方法,獲取與給定鍵相關聯的值,也可以在字典中不包含給定鍵的情況下設定相應的鍵值
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
printd
printd.setdefault('one',1)
printd.setdefault('four',4)
printd
運算結果:
{'three':3,'two':2,'one':1}
{'four':4,'three':3,'two':2,'one':1}
>>>
3.11 update函數:用一個字典更新另外一個字典
# _*_ coding:utf-8 _*_
d={
'one':123,
'two':2,
'three':3
}
printd
x={'one':1}
d.update(x)
printd
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':3,'two':2,'one':123}
{'three':3,'two':2,'one':1}
>>>
3.12 values和itervalues函數:values以列表的形式返回字典中的值,itervalues返回值得迭代器,由於在字典中值不是唯一的,所以列表中可以包含重復的元素
# _*_ coding:utf-8 _*_
d={
'one':123,
'two':2,
'three':3,
'test':2
}
printd.values()
運算結果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
[2,3,2,123]
>>>
㈧ python字典的基本操作
python字典的基本操作如下:
查詢字典
字典裡面可以嵌套字典,嵌套列表。
㈨ Python字典創建、基本操作以及常用方法
創建一個空字典自需要一對大括弧即可,從已有的鍵-值對映射或關鍵字參數創建字典需要使用 dict 函數(類)
把一個列表轉為字典,列表的每一項都是長度為2的序列。
還可使用 關鍵字實參 (**kwargs)來調用這個函數,如下所示:
字典的基本操作與序列十分相似:
字典與序列的不同:
方法 clear 刪除所有的字典項(key-value)。
復制,得到原字典的一個新副本。
效果等同於調用 dict(d) 創建新字典。
() 執行的是 淺復制 ,若字典的值是一個可變對象,那麼復制以後,相同一個鍵將關聯到同一個對象,修改該對象,將同時修改兩個字典。
模塊中的函數deep 可執行深復制。
方法fromkeys 創建一個新字典,其中包含指定的鍵,且每個鍵對應的值都是None,或者可以提供一個i額默認值。
方法get 為訪問字典項提供了寬松的環境。通常,如果你試圖訪問字典中沒有的項,將引發錯誤,而get直接返回None,或者可設置默認返回值。
當字典中不存在指定鍵時, setdefault(k,v) 添加一個指定鍵-值對;且返回指定鍵所關聯的值。
這三個方法返回值屬於一種名為 字典視圖 的特殊類型。字典視圖可用於迭代。另外,還可確定其長度以及對其執行成員資格檢查。
這三個方法自大的特點是不可變,當你的介面試圖對其他用戶提供一個只讀字典,而不希望他們修改的時候,這三個方法是很有用的;而且當原字典發生改變時,這些方法返回的對象也會跟著改變。
方法 pop 可用於獲取與指定鍵相關聯的值,並將該鍵-值對從字典中刪除。
popitem隨機刪除一個鍵-值對,並返回一個二維的元組 (key, value) ,因為字典是無序的,所以其彈出的順序也是不確定的。
書上說,這個方法在大數據量時執行效率很高,但沒有親測。
方法update 使用一個字典中的項來更新另一個字典。