字典由键(key)和对应值(value)成对组成。基本语法如下:
dict={ 'Alice': '2341' , 'Beth' : '9102' , 'Cecil' : '3258' }
注意:
1.每个键(key)与值(value)用冒号( :)隔开,每对用逗号分割,整体放在{}中。
2.键必须独一无二,但值不必
3.值可以取任何数据类型,但必须是不可变的,如字符串、数组或元组
字典键的特性:
字典值可以没有限制地取任何python对象,既可以是标准的对象,也可以是用户定义的,但键不行。
1.不允许同一个键出现两次。创建时如果同一个键被赋值两次,只有后一个值会被记住:
dict = {'Name':'Zara','Age': 7,'Name':'Manni'}
print"dict['Name']: ", dict['Name']
#以上实例输出结果:
#dict['Name']: Manni
2.键必须不可变,所以可以用数、字符串或元组充当,列表不行:
dict = {['Name']:'Zara','Age': 7}
print"dict['Name']: ", dict['Name']
#以上实例输出结果:
#TypeError: list objects are unhashable
python字典内置函数:
cmp(dict1, dict2)
#比较两个字典元素 如果两个字典的元素相同返回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))
以上实例输出结果为:
Return Value : -1
Return Value : 1
Return Value : 0
len(dict)#计算字典元素个数,即键的总数
str(dict)#输出字典可打印的字符串表示
type(variable)#返回输入的变量类型,如果变量是字典就返回字典类型
Python字典包含了以下内置方法:
radiansdict.clear() #删除字典内所有元素
radiansdict.copy() #返回一个字典的浅复制
radiansdict.fromkeys() #创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值radiansdict.get(key, default=None) #返回指定键的值,如果值不在字典中返回default值radiansdict.has_key(key)#如果键在字典dict里返回true,否则返回false
radiansdict.items() #以列表返回可遍历的(键, 值) 元组数组
radiansdict.keys() #以列表返回一个字典所有的键
radiansdict.setdefault(key, default=None) #和get()类似, 但如果键不已经存在于字典中,将会添加键并将值设为defaultradiansdict.update(dict2)#把字典dict2的键/值对更新到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]))
输出打印:
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