Python字典dict基础知识点总结

Python字典dict基础知识点总结

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time  : 2020/4/21 19:52
# @Author: xuhui
# @File  : Dict.py

print()
print("`````aaaaaaaaa`````")
print()

# !!!字典的创建,字典又叫做哈希表,与列表一样均为可变容器
# 1.通过大括号{}将键值对(key: value)包裹-->{key1: value1, key2: value2}
# 2.字典中的key值是唯一的,不能重复,每一个key对应一个哈希值
# 3.字典的key值是大小写敏感的,即"IP"与"Ip"是两个不同的key
# 4.只有不可变的内容才可以做哈希(即key)
#   之前我们提到过元组和字符串都是不可修改的,一般我们使用str作为key,有时候也使用tuple作为key
device = {"IP": "127.0.0.1", "hostname": "local", "port": "80", "webServer": "tomcat", "App": "IDEA"}

print()
print("`````bbbbbbbbb`````")
print()

# !!!字典的访问
# !注意字典与列表、元组、字符串不同,字典中的元素没有确定的顺序,即不能通过下标取访问字典元素
# 这种通过key访问value的方式能够便于我们去了解value的含义
# print(device[0])
# -->Traceback (most recent call last):
# -->File "E:/A-PythonProject/E-BP3-Test/Dict.py", line 25, in <module>
# -->print(device[0])
# -->KeyError: 0     #报错的意思是说没有0这个key存在,所以在中括号[]中只能输入key作为查询信息
print("```(1)```")
#    方法一:dict_x[key_x],通过该方式访问dict_x,若该字典中不存在key_x这个键,会报错,与27行到30行错误一样
print(device["IP"])
#    方法二:dict_x.get(key_x,value_x),通过该方式访问dict_x(value_x可不写,默认为None)
#          若该字典中不存在key_x这个键,
#             不会报错,会返回value_x(没写,默认返回None),告诉我们在dict_x中不存在key_x这个键,!不会改变原字典
#          若该字典中存在key_x这个键,返回key_x对应的value值
print(device.get("hostname"))
print(device.get("uu"))
print(device.get("IP", "localhost"))
print(device.get("Ip", "localhost"))
print(device)
# dict_x.keys(),获取dict_x中全部key值,并存入到一个列表当中
print("```(2)```")
print(device.keys())
# dict_x.values(),获取dict_x中全部value值,并存入到一个列表当中
print("```(3)```")
print(device.values())
# dict_x.items(),获取dict_x中全部键值对,并将键值对以元组的形式存入到一个列表当中
print("```(3)```")
print(device.items())

print()
print("`````ccccccccc`````")
print()

# !!!更改字典元素
# dict_x[key_x]=value_x,key_x要在dict_x存在
device["IP"] = "localhost"
print(device.get("IP"))

print()
print("`````ddddddddd`````")
print()

# !!!向字典中新增元素
# dict_x[key_x]=value_x,dict_x中不存在key_x,则会在dict_x新增一对键值key_x: value_x
print(device)
device["Ip"] = "localhost"
print(device)


print()
print("`````eeeeeeeee`````")
print()

# !!!删除字典中的元素
#    方法一:del dict_x[key_x],如果dict_x中不存在key_x,会报错,与27行到30一样
print("```(1)```")
print(device)
del device["Ip"]
print(device)
#    方法二:dict_x.pop(key_x)
print("```(2)```")
device.pop("IP")
print(device)

发布了7 篇原创文章 · 获赞 4 · 访问量 169

猜你喜欢

转载自blog.csdn.net/weimofanchen/article/details/105671330