一、字典的定义
- 键必须是唯一的,但值则不必。
- 字典以 关键字 为索引,关键字通常是字符串或数字,也可以是其他任意不可变类型。
- 只包含字符串、数字、元组的元组,也可以用作关键字。但如果元组直接或间接地包含了可变对象,就不能用作关键字。
- 列表不能当关键字,因为列表可以用索引、切片、append() 、extend() 等方法修改。
dict1 = {'key1':456,'key2':'hello','key3':456}
dict2 = {'key1':456,'key2':'hello','key2':'haha'}
print(dict1,dict2)
dict3 = {'key1':456,789:123}
print(dict3)
dict4 = {"('physics', 'chemistry', 1997, 2000)":123}
print(dict4)
list1 = [1,2,3]
tuple1 = (1,2,list1)
print(type(tuple1))
dict5 = {tuple1:123}
print(dict5)
dict6 = {[4,5]:123}
print(dict6)
二、字典的常用操作
- 创建空字典
emptyDict1 = {}
emptyDict2 = dict()
- 访问字典里的值
dict1 = {'key1':'value1','key2':'value2'}
print(dict1['key2'])
- 修改字典
dict2 = {'key1':'value1','key2':'value2'}
dict2['key1']='修改'
print(dict2)
- 删除字典
dict3 = {'key1':'value1','key2':'value2'}
del dict3['key1']
print(dict3)
dict3.clear()
print(dict3)
del dict3
print(dict3)
- dict.items()
dict4 = {'key1':'value1','key2':'value2'}
for k,v in dict4:
print(k,v)
for k,v in dict4.items():
print(k,v)
print(dict4.keys())
print(dict4.values())
print(dict4.items())
print(type(dict4.items()))
print(type(list(dict4.items())))
d={1:"a",2:"b",3:"c"}
result=[]
for k,v in d.items():
result.append(k)
result.append(v)
print(result)
|