Python基础-字典dict

Python 94次浏览 本站
#字典由多个键值对组成,每个键和它的值之间用":"隔开,整个字典用{}括起来。
user={"zhangsan":22,"lisi":25,"wangwu":30}
print(type(user))
print(user)
#输出:<class 'dict'>
#输出:{'zhangsan': 22, 'lisi': 25, 'wangwu': 30}

#1.dict函数:通过映射将其他序列转换为字典
a=[("name","zhangsan"),("age",28)]
dic=dict(a)
print(dic)
#输出:{'name': 'zhangsan', 'age': 28}

b=dict(name="lisi",age=25)
print(b)
#输出:{'name': 'lisi', 'age': 25}

#2.遍历dict
user={"zhangsan":22,"lisi":25,"wangwu":30}
#2.1 遍历元素
for u in user :
    print(u,":",user[u])

#2.2 遍历key
keys =user.keys()
for key in keys:
    print(key)

#2.3 遍历value
values = user.values()
for value in values:
    print(value)

#2.4 遍历key和value
for key,value in user.items():
    print(key,":",value)

#2.5 遍历字典项
items = user.items()
for item in items:
    print(item) 

#3.clear()方法:清除字典中的所有项,这个是原地操作,无返回值
user={"zhangsan":22,"lisi":25,"wangwu":30}
user.clear()
print(len(user))
#输出:0

#4.pop()方法:用于获取给定键的值,然后将这个键-值从字典中删除
user={"zhangsan":22,"lisi":25,"wangwu":30}
print(user.pop("zhangsan"))
print(user)
#输出:22
#输出:{'lisi': 25, 'wangwu': 30}

#5.update方法():利用一个字典项更新 另外一个字典
user={"zhangsan":22,"lisi":25,"wangwu":30}
zhangsan={"zhangsan":33}
user.update(zhangsan)
print(user)

user["zhangsan"]=44
print(user)
#输出:{'zhangsan': 33, 'lisi': 25, 'wangwu': 30}
#输出:{'zhangsan': 44, 'lisi': 25, 'wangwu': 30}

#6.字典的格式化字符串
template='''<html>
<head><title>%(title)s</title></head>
<body>%(body)s</body>
</html>'''
data={"title":"测试标题","body":"测试body"}
print(template % data)
#输出:<html>
#<head><title>测试标题</title></head>
#<body>测试body</body>
#</html> 

发表评论

电子邮件地址不会被公开。 必填项已用*标注