Python从0到1——字典(dict)操作
其他常用操作见:https://blog.csdn.net/qq_33302004/article/details/112859327
目录
一、字典结构
字典就是dict类型, 我认为可以理解为对象,或者jsonObeject
# 1.字典的定义({}用于定义字典,[]用于定义list)
temp = {}
print(type(temp))
# 2.字典的结构操作
# 字典结构:key-value
temp = {}
temp["python"] = 123 # 需要先对temp定义,才可以赋键值对
print(temp)
temp["c++"] = 345
print(temp)
print(temp["c++"]) # 必须用键值做索引,字典中并没有下标的概念
temp = {"math":98,"english":100, "chinese":99}
print(temp)
一、字典操作
# 1.dict嵌套list
studentList = ['tom','bob','lily']
myClass = {"students":studentList}
print(myClass)
myClass["classNumber"] = 17
myClass["description"] = "一个好班级"
print(myClass)
# 2.字典嵌套字典
mySchool = {'class1':myClass, 'class2':myClass}
print(mySchool)
mySchool['class2']['students'] = ['jack','sky','xiaoming']
mySchool['class2']['classNumber'] = 16
mySchool['class2']['description'] = '一个活跃的班级'
print(mySchool)
# 3.另外一种字典的声明方式(不太常用)
temp =dict([('math',98), ('chinese',99)])
print(temp)
# 4.通过get函数获取dict中的值,如果没有可以自己处理
temp =dict([('math',98), ('chinese',99)])
print(temp.get('math'))
print(temp.get('english'))
print(temp.get('english','不存在'))
print(temp.get('math','不存在'))
# 5.pop类似于list中的pop,返回键对应的值,并且将该键值对从dict中删除
temp =dict([('math',98), ('chinese',99)])
print(temp.pop('math'))
print(temp)
# 6.删除(也类似于list, 但是只有del,没有remove)
temp =dict([('math',98), ('chinese',99)])
del temp['math']
print(temp)
# 7.字典更新update(用于:改变dict中的某些值、某些值不变、再新增一些项)
temp = {'math':98,'chinese':99}
temp2 = {'math':100, 'english':78}
temp.update(temp2) # 使用temp2更新temp,相同项使用temp2的值,不同项全部保留
print(temp)
# 8.判断元素是否在字典中(类似于list和字符串的操作)
temp = {'math':98,'chinese':99}
print('math' in temp)
print('english' in temp)
# 9.打印所有的键、值、键值对
temp = {'math':98,'chinese':99}
print(temp.keys())
print(temp.values())
print(temp.items())