ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python 字典 dict

2021-08-10 02:31:10  阅读:187  来源: 互联网

标签:python age thisdict year print dict 字典


字典(Dictionary)

字典是一个无序、可变和有索引的集合。在 Python 中,字典用花括号编写,拥有键和值。

字典基础

#创建字典 dict
thisdict={
    "age":"18",
    "year":'2021',
    "month":"8"
}


#访问项目
#您可以通过在方括号内引用其键名来访问字典的项目:
#获取 "model" 键的值:
print(thisdict["year"])#2021

#get() 方法一样可以获取项目
print(thisdict.get('month'))#8


#更改值
#您可以通过引用其键名来更改特定项的值:
thisdict["age"]=2099
print(thisdict["age"])#2099

#for循环遍历遍历字典dict  x key值 
for x in thisdict:
    print(x,thisdict[x])


#values() 函数返回字典的值
for x in thisdict.values():
    print(x)

#items() 函数返回遍历键和值
for x,y in thisdict.items():
    print(x,y)


#in 关键字 检查指定值是否存在dict中
print('html' in thisdict)#False

#len() 方法测试字典长度
print(len(thisdict))#3


#添加项目 通过使用新的索引键并为其赋值,可以将项目添加到字典中:
thisdict['color']='blue'
print(thisdict)

#删除项目 有几种方法删除项目
#pop()方法删除具有指定键名的项
thisdict.pop('color')
print(thisdict)#{'age': 2099, 'year': '2021', 'month': '8'}

#popitem() 方法删除最后插入的项目(3.7版本之前的版本中,随机删除项目)
thisdict.popitem()
print(thisdict)#{'age': 2099, 'year': '2021'}

#del 关键字 删除 可以删除指定键名的字典  也可以删除整个字典
del thisdict['age']
print(thisdict) #{'year': '2021'}

del thisdict
# print(thisdict) #报错 NameError: name 'thisdict' is not defined


#clear() 方法清空dict
thisdict={'age': 2099, 'year': '2021', 'month': '8'}
thisdict.clear()
print(thisdict)#{}

#复制字典 dict
#copy() 复制字典
thisdict={'age': 2099, 'year': '2021', 'month': '8'}
mydict=thisdict.copy()
print(mydict)#{'age': 2099, 'year': '2021', 'month': '8'}
print(mydict is thisdict)#False
print(id(mydict),id(thisdict))#id() 方法 查看内存地址

#dict() 构造函数 生成dict
youdict=dict(thisdict)
print(thisdict==youdict,thisdict is youdict)#True False


#dict() 构造函数创建新的字典:
dictOne=dict(color="blue")#{'color': 'blue'}
print(dictOne)#
View Code

 

标签:python,age,thisdict,year,print,dict,字典
来源: https://www.cnblogs.com/lvlisn/p/15121875.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有