Python字典练习
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python字典练习相关的知识,希望对你有一定的参考价值。
#字典:通过名字引用值得数据结构 键/值
from copy import deepcopy
#######################################################
"""
#1 创建和使用字典
phone = {"张三":"1234567","lisi":"23414","lisi":"23414","wangwu":"432653250"}
print(phone)
print(phone["张三"])#键是唯一的
print(phone["lisi"])
#dict函数创建字典
item = [(‘name‘,"zhangsan"),(‘age‘,42)]
d = dict(item)
print(d)
"""
"""
C:\python3.7\python.exe D:/Python-Test/qiubai/qiubai/Test3.py
{‘张三‘: ‘1234567‘, ‘lisi‘: ‘23414‘, ‘wangwu‘: ‘432653250‘}
1234567
23414
{‘name‘: ‘zhangsan‘, ‘age‘: 42}
"""
#######################################################
"""
#2 字典示例
people = {
‘zhangsan1‘:{
‘phone‘:12345,
‘addr‘:"beijing"
},
‘zhangsan2‘:{
‘phone‘:12345,
‘addr‘:"beijing"
},
‘zhangsan3‘:{
‘phone‘:12345,
‘addr‘:"beijing"
},
‘zhangsan‘:{
‘phone‘:12345,
‘addr‘:"beijing"
}
}
labers = {
‘phone‘:‘电话号码‘,
‘addr‘:‘地址‘
}
name = input(‘请输入姓名:‘)
request = input(‘地址a还是电话p?‘)
if request == ‘p‘:
key =‘phone‘
if request == ‘a‘:
key = ‘addr‘
if name in people:
print("%s‘s %s is %s" % (name, labers[key],people[name][key]))
"""
"""
C:\python3.7\python.exe D:/Python-Test/qiubai/qiubai/Test3.py
请输入姓名:zhangsan
地址a还是电话p?p
zhangsan‘s 电话号码 is 12345
"""
#######################################################
‘‘‘
#3 字符串格式化
#转化说明符%(key)s --> % data
tmp = """
<head>
<title>%(title)s<title/>
</head>
<body>
<h1>%(title)s</h1>
<p>%(text)s</p>
</body>
"""
data = {
‘title‘:"My Home Page",
‘text‘:"Welcome to my page"
}
print(tmp % data)
‘‘‘
"""
C:\python3.7\python.exe D:/Python-Test/qiubai/qiubai/Test3.py
<head>
<title>My Home Page<title/>
</head>
<body>
<h1>My Home Page</h1>
<p>Welcome to my page</p>
</body>
"""
#######################################################
"""
#4 字典方法
#4.1 clear清除字典所有项
data1 = {
}
data1[‘name‘] = "zhangsan"
data1[‘age‘] = 45
print(data1)
data1.clear()
print(data1)
"""
"""
C:\python3.7\python.exe D:/Python-Test/qiubai/qiubai/Test3.py
{‘name‘: ‘zhangsan‘, ‘age‘: 45}
{}
"""
#######################################################
‘‘‘
#4.2 copy浅复制
x = {
‘name‘:‘zhangsan‘,
‘love‘:[‘reading‘,‘play‘,‘sing‘]
}
y = x.copy()
print(x)
print("复制一份:",y)
#替换
y[‘name‘] = ‘lishi‘
#修改