字典的创建及操作方法
2019-06-23 本文已影响68人
Mouse_Hang
1、字典的特点
字典:是python中的无序的对象集合。字典与列表的区别是:字典中的数据是无序的,而且字典中的元素是依靠键来查询的;列表中的数据是有序的,并且是通过索引查询。
注意:字典的键必须是不可变类型,因为在创建字典时,会先对键进行hash(),用以确定字典在内存中是如何被保存的,而hash()只能传入不可变类型的参数。而字典的值可以是任意类型的数据。
特点:
1、字典是任意对象的无序集合;
2、字典是通过键查找元素值的;
3、字典是异构、可嵌套的;
4、字典是可变的映射类型;
5、字典是一个对象引用表,其中存储的是对象的引用。
2、常用操作方法
1)创建字典,从dic_test2的输出中可以看出字典是无序的。
dic_test1 = {}
print(dic_test1) # 输出为:{}
dic_test2 = {"name": "xiaoming", "age": 23, "weight": 65, "height": 185}
print(dic_test2) # 输出为:{'name': 'xiaoming', 'age': 23, 'weight': 65, 'height': 185}
2)字典的增、删、查、改
dic_test2["grade"] = 99 # 添加元素
print(dic_test2) # 输出为:{'name': 'xiaoming', 'age': 23, 'weight': 65, 'height': 185, 'grade': 99}
dic_test3 = {"money": 123456789}
dic_test2.update(dic_test3) # 通过update()方法添加一个字典
print(dic_test2) # 输出为:{'name': 'xiaoming', 'age': 23, 'weight': 65, 'height': 185, 'grade': 99, 'money': 123456789}
print(dic_test2["name"]) # 根据键查询元素值输出为:xiaoming
dic_test2.pop("weight") # 删除元素
print(dic_test2) # 输出为:{'name': 'xiaoming', 'age': 23, 'height': 185, 'grade': 99}
del dic_test2["height"] # 删除元素
print(dic_test2) # 输出为:{'name': 'xiaoming', 'age': 23, 'grade': 99}
dic_test2["name"] = "xiaowang" # 原位修改元素
print(dic_test2) # 输出为:{'name': 'xiaowang', 'age': 23, 'grade': 99}
3)其他常用方法
# keys()方法返回字典的所有键,并将其放入在一个列表中
print(list(dic_test2.keys())) # 输出为:['name', 'age', 'grade']
# values()方法返回字典的元素值
print(list(dic_test2.values())) # 输出为:['xiaowang', 23, 99]
# items()方法返回字典的键和元素值的元组对列表
print(list(dic_test2.items())) # 输出为:[('name', 'xiaowang'), ('age', 23), ('grade', 99)]