- 字典的创建
d1 = {} #创建空字典,没有任何元素的大括号即为字典
d2 = dict() #创建空字典
d3 = {"one":1,"two":2,"three":3} #键与至之间用冒号"分开,键值对之间用逗号,分开
d4 = dict(one=1,two=2,three=3) #注意此时key不要加引号
print(type(d1))
print(type(d2))
print(d3)
print(d4)
输出为
<class 'dict'> <class 'dict'> {'one': 1, 'two': 2, 'three': 3} {'one': 1, 'two': 2, 'three': 3}
- 字典的特征
字典是序列类型:按照key值哈希排列(list, set, dict不可哈希,所以不能所谓字典的key),但是不能分片也没有索引。
- 遍历字典
# 遍历字典,字典以为大括号为标识符 dic1 = {'one':1,'two':2,'three':3} for k,v in dic1.items(): print(k,'...',v) print("*"*20) # 遍历双层列表,非字典 dic2 = [['one',1],['two',2],['three',3]] for k,v in dic2: print(k,'...',v)
输出为
one ... 1 two ... 2 three ... 3 ******************** one ... 1 two ... 2 three ... 3
- 其他
dic1 = {'one':1,'two':2,'three':3, 'two':4} #赋予多个相同的键值,只有最后一个会被记住
print(dic1['two']) #打印的结果是4
dic1.keys() #输出字典所有的键值
dic1.values() #输出字典所有值
dic1.items() #以列表形式返回可遍历 (键,值)元组列表
del dic1['two'] #删除键值为two的条目
dic1.clear() #删除字典