读取和拷贝
if __name__ == '__main__':
print()
dictInfo = {1: "This is one", 2: "", 3: '', 5: "This is five"}
# 字典的读取
assert (len(dictInfo[1]) > 0)
assert (len(dictInfo[2]) <= 0)
assert (len(dictInfo[3]) <= 0)
if 4 in dictInfo:
assert (len(dictInfo[4]) <= 0)
else:
print("4 is not in dictInfo")
# 字典的引用拷贝
# (1) 直接赋值,对象的引用(别名)
dic1 = {"Name": "HaiCoder", "Age": 100, "Score": 99.5}
dic2 = dic1
dic2["Name"] = "Demo"
print("dic1", json.dumps(dic1))
print("dic2", json.dumps(dic2))
# print(json.dumps(dic1, sort_keys=True, indent=4, separators=(',', ':')))
# (2) copy函数 拷贝父对象,不会拷贝对象的内部的子对象,数组也是个引用
dic1 = {"Name": "HaiCoder", "Age": 100, "Score": 99.5, "phone": [10086, 10010]}
dic2 = dic1.copy()
dic2["Name"] = "Demo"
print("dic1", json.dumps(dic1))
print("dic2", json.dumps(dic2))
dic1["phone"].append(10000)
dic2["phone"].append(20000)
print("dic1", json.dumps(dic1))
print("dic2", json.dumps(dic2))
# (3) copy.deepcopy, 完全拷贝了父对象及其子对象
dic1 = {"Name": "HaiCoder", "Age": 100, "Score": 99.5, "phone": [10086, 10010]}
dic2 = copy.deepcopy(dic1)
dic2["Name"] = "Demo"
print("dic1", json.dumps(dic1))
print("dic2", json.dumps(dic2))
dic1["phone"].append(10000)
dic2["phone"].append(20000)
print("dic1", json.dumps(dic1))
print("dic2", json.dumps(dic2))
#(4) copy.copy 浅拷贝
a = [1, 2, 3, 4, ['a', 'b']] # 原始对象
b = a # 赋值,传对象的引用
c = copy.copy(a) # 对象拷贝,浅拷贝
d = copy.deepcopy(a) # 对象拷贝,深拷贝
a.append(5) # 修改对象a
a[4].append('c') # 修改对象a中的['a', 'b']数组对象
print('a = ', a) # [1, 2, 3, 4, ['a', 'b', 'c'], 5]
print('b = ', b) # [1, 2, 3, 4, ['a', 'b', 'c'], 5]
print('c = ', c) # [1, 2, 3, 4, ['a', 'b', '4'], 5]
print('d = ', d) # [1, 2, 3, 4, ['a', 'b']]
文章来源地址https://www.toymoban.com/news/detail-507029.html
创建和类型
if __name__ == '__main__':
print()
# {} 创建字典详解
dic = {"Name": "HaiCoder", "Age": 100, "Score": 99.5}
print(dic)
print(type(dic)) # 使用 type() 函数,获取字典类型
# 使用 fromkeys()
# dictName = dict.fromkeys(list,value=None), list 参数表示字典中所有键的列表,value 参数默认为 None,表示所有键对应的值
keys = ("Name", "Age", "Score")
dic = dict.fromkeys(keys)
print(dic)
dic["Name"] = 1
dic["Age"] = "2"
dic["Score"] = [1, "2"]
dic["Phone"] = {10086, 10010}
print(dic)
print(type(dic["Score"]), type(dic["Phone"])) # Score是list,Phone是set
# 使用 dict() 创建字典详解
# dic = dict(one=1, two=2, three=3) # 用这种方式创建字典的 key 不需要加双引号
dic = dict(Monday=1, Tuesday=2, Wednesday=3, Thursday=4, Friday=5)
print(dic)
访问和遍历
if __name__ == '__main__':
print()
dic = {"Name": "HaiCoder", "Age": 100, "Score": 99.5}
# (1)使用key作为下标访问,如果键不存在,程序会抛出异常
print(dic["Name"])
# (2)使用 get() 方法访问,如果键不存在,程序会不会抛出异常,而是返回一个空值,同时该方法可以设置键不存在时,使用的默认值。
print(dic.get("Name"), dic.get("name", "nil"), dic.get("name"))
if dic.get("name") is None:
print("name not in dic")
# (3)使用 items() 访问,返回是一个 key 对应一个 value 的元祖的列表的形式
print(dic.items())
# (4)使用 keys() 访问,返回的是字典的所有的key list
print(dic.keys())
# (5)使用 values() 访问,返回的是字典的所有的val list
print(dic.values())
# 遍历
print("------(1)遍历key------")
for key in dic:
print(key)
print("------(2)遍历key------")
for key in dic.keys(): # for key in a和 for key in a.keys() 完全等价
print(key)
print("------(3)遍历val------")
for value in dic.values():
print(value)
print("------(4)遍历k-v------")
for kv in dic.items():
print(kv, kv[0], kv[1])
# 为啥这里的key和value必须是string
dic = {"Name": "HaiCoder", "Age": "100", "Score": "99.5"}
print("------遍历k-v------")
for (key, value) in dic.items():
print(key + ':' + value)
for key, value in dic.items():
print(key + ':' + value)
删除和弹出
if __name__ == '__main__':
print()
# 删除单个元素、删除整个元素
dic = {"Name": "HaiCoder", "Age": 100, "Score": 99.5}
# del dic["Phone"] 报错
del dic["Name"]
print("dic", dic)
del dic
# print("dic", dic) 报错
# 弹出一个元素
# 使用 pop 从字典中弹出不存在的元素
dic = {"Name": "HaiCoder", "Age": 100, "Score": 99.5}
# print("dic Before pop name", dic)
# item = dic.pop("name") 报错
# print("name =", item, "dic After pop name =", dic)
print("dic Before pop Name", dic)
item = dic.pop("Name")
print("Name =", item, "dic After pop Name =", dic)
dic = {"Name": "HaiCoder"}
print("dic Before pop Name", dic)
item = dic.pop("Name")
print("Name =", item, "dic After pop Name =", dic) # {}
# 使用 popitem 从字典中随机返回一个元素
dic = {"Name": "HaiCoder", "Age": 100, "Score": 99.5}
print("dic before popitem =", dic)
item = dic.popitem()
print("Pop Item =", item, "dic after popitem =", dic)
# 从空字典中弹出元素,程序报错
# dic = {}
# item = dic.popitem() 报错
# print("Pop Item =", item, "dic after popitem =", dic)
文章来源:https://www.toymoban.com/news/detail-507029.html
到了这里,关于python字典学习的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!