创建字典:
>>> d={'one':1,'two':2}
>>> d
{'one': 1, 'two': 2}
字典的访问:
>>> d['one']
1
在字典中添加键值:
>>> d['three']=3
>>> d
{'one': 1, 'two': 2, 'three': 3}
在字典中删除键值:
>>> del d['two']
>>> d
{'one': 1, 'three': 3}
遍历字典:
>>> for key in d:
print(d[key])
1
3
>>> for key in d:
print(key)
one
three
对字典中的键重新赋值:
>>> d
{'one': 1, 'three': 3}
>>> d['one']=11
>>> d
{'one': 11, 'three': 3}
len() 获得字典的长度
min()获得键中最小的那个键(注意,是键,不是键值)
max()与min()相似
>>> d
{'one': 1, 'three': 3, 'two': 2, 'four': 4}
>>> len(d)
4
>>> min(d)
'four'
>>> max(d)
'two'
>>> sum(d)
Traceback (most recent call last):
File "<pyshell#116>", line 1, in <module>
sum(d)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
sum()操作对字典无效
get()函数及其应用:
>>> d.get('one') #尝试得到one的值
1
>>> d.get('five') #尝试得到five的值,若five不存在,也不报异常
>>> d.get('five',0) #尝试得到five的值,若five不存在,则返回0
0
>>> d.get('four',0) #尝试得到five的值,若four不存在,则返回0,若存在则返回four的值
4
统计某列表中出现数字的次数:
list_1=[1,2,3,4,2,3,4,3,4,5,6,5,8,9,2,3,5,3,4,3]
d={}
for i in list_1:
if i in d:
d[i] += 1
else:
d[i] = 1
print(d)
output={1: 1, 2: 3, 3: 6, 4: 4, 5: 3, 6: 1, 8: 1, 9: 1}
list_1=[1,2,3,4,2,3,4,3,4,5,6,5,8,9,2,3,5,3,4,3]
d={}
for i in list_1:
d[i]=d.get(i,0)
print(d)
output={1: 1, 2: 3, 3: 6, 4: 4, 5: 3, 6: 1, 8: 1, 9: 1}