python字典操作

本文详细介绍了Python字典的创建、删除、元素访问等操作,包括get()、setdefault()方法,update()方法以及pop()、popitem()、clear()等方法的使用。此外,还探讨了标准库collections中的orderedDict、defaultdict和Counter类,它们分别提供了记住插入顺序、默认值和频次统计的功能。
摘要由CSDN通过智能技术生成

字典创建、删除

aDict = {
  'server':'db.diveintopython3.org','database':'mysql'}
aDict
{'database': 'mysql', 'server': 'db.diveintopython3.org'}
#空字典
x = dict()# x={}
#键值表创建
keys = ['a','b', 'c', 'd']
values = [1, 2, 3, 4]
dictionary = dict(zip(keys,values))
dictionary
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
# 关键字参数创建字典
d = dict(name='Dong', age=39)
d
{'age': 39, 'name': 'Dong'}
# 以给定内容为“键”创建“值”为空的字典
aDict = dict.fromkeys(['name','age','sex'])
aDict
{'age': None, 'name': None, 'sex': None}
#推导式生成
{i:str(i) for i in range(1,5)}
{1: '1', 2: '2', 3: '3', 4: '4'}

字典元素的访问

aDict = {
  'age':39,'score':[98, 97],'name': 'Dong','sex':'male'}
def fun(x):
    if x in aDict:
        print(aDict[x])
    else:
        print('Not Exists.')
fun('Age')
Not Exists.

                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值