- 字典的创建
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
thr