python-字典

本文详细介绍了Python字典的创建、访问、添加键值、删除键值、遍历及键的重新赋值等操作,并重点讲解了get()函数的应用,包括如何利用get()统计列表中数字出现的次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建字典:

>>> 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}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值