字典由鍵(key)和對(duì)應(yīng)值(value)成對(duì)組成。基本語法如下:
dict={ 'Alice': '2341' , 'Beth' : '9102' , 'Cecil' : '3258' }
注意:
1.每個(gè)鍵(key)與值(value)用冒號(hào)( :)隔開,每對(duì)用逗號(hào)分割,整體放在{}中。
2.鍵必須獨(dú)一無二,但值不必
3.值可以取任何數(shù)據(jù)類型,但必須是不可變的,如字符串、數(shù)組或元組
字典鍵的特性:
字典值可以沒有限制地取任何python對(duì)象,既可以是標(biāo)準(zhǔn)的對(duì)象,也可以是用戶定義的,但鍵不行。
1.不允許同一個(gè)鍵出現(xiàn)兩次。創(chuàng)建時(shí)如果同一個(gè)鍵被賦值兩次,只有后一個(gè)值會(huì)被記?。?/p>
dict = {'Name':'Zara','Age': 7,'Name':'Manni'}
print"dict['Name']: ", dict['Name']
#以上實(shí)例輸出結(jié)果:
#dict['Name']: Manni
2.鍵必須不可變,所以可以用數(shù)、字符串或元組充當(dāng),列表不行:
dict = {['Name']:'Zara','Age': 7}
print"dict['Name']: ", dict['Name']
#以上實(shí)例輸出結(jié)果:
#TypeError: list objects are unhashable
python字典內(nèi)置函數(shù):
?cmp(dict1, dict2)
#比較兩個(gè)字典元素?如果兩個(gè)字典的元素相同返回0,如果字典dict1大于字典dict2返回1,如果字典dict1小于字典dict2返回-1
dict1 = {'Name': 'Zara', 'Age': 7}
dict2 = {'Name': 'Mahnaz', 'Age': 27}
dict3 = {'Name': 'Abid', 'Age': 27}
dict4 = {'Name': 'Zara', 'Age': 7}
print ("Return Value : %d" % cmp (dict1, dict2))
print ("Return Value : %d" % cmp (dict2, dict3))
print ("Return Value : %d" % cmp (dict1, dict4))
以上實(shí)例輸出結(jié)果為:
Return Value : -1
Return Value : 1
Return Value : 0
len(dict)#計(jì)算字典元素個(gè)數(shù),即鍵的總數(shù)
str(dict)#輸出字典可打印的字符串表示
type(variable)#返回輸入的變量類型,如果變量是字典就返回字典類型
Python字典包含了以下內(nèi)置方法:
radiansdict.clear()????#刪除字典內(nèi)所有元素
radiansdict.copy()????#返回一個(gè)字典的淺復(fù)制
radiansdict.fromkeys()????#創(chuàng)建一個(gè)新字典,以序列seq中元素做字典的鍵,val為字典所有鍵對(duì)應(yīng)的初始值radiansdict.get(key, default=None)????#返回指定鍵的值,如果值不在字典中返回default值radiansdict.has_key(key)#如果鍵在字典dict里返回true,否則返回false
radiansdict.items()????#以列表返回可遍歷的(鍵, 值) 元組數(shù)組
radiansdict.keys()????#以列表返回一個(gè)字典所有的鍵
radiansdict.setdefault(key, default=None)????#和get()類似, 但如果鍵不已經(jīng)存在于字典中,將會(huì)添加鍵并將值設(shè)為defaultradiansdict.update(dict2)#把字典dict2的鍵/值對(duì)更新到dict里
radiansdict.values()????#以列表返回字典中的所有值
python leetcode 中?136.?Single Number題目如下:
Given anon-emptyarray of integers, every element appearstwiceexcept for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input:[2,2,1]Output:1
Example 2:
Input:[4,1,2,1,2]Output:4
answer:
class Solution:
? ? def singleNumber1(self, nums):
? ? ? ? dic = {}
? ? ? ? for num in nums:
? ? ? ? ? ? dic[num] = dic.get(num, 0)+1
? ? ? ? ? ? print(dic[num])
? ? ? ? print(dic.items())
? ? ? ? for key, val in dic.items():
? ? ? ? ? ? if val == 1:
? ? ? ? ? ? ? ? return key
a=Solution()
print(a.singleNumber1([2,2,1,1,4]))
輸出打?。?/p>
?print(dic[num]):
1
2
1
2
1
? print(dic.items()):
dict_items([(2, 2), (1, 2), (4, 1)])
print(a.singleNumber1([2,2,1,1,4])):
4??