Python字典基本操作

python学习网 2018-08-17 22:25:02
  • 遍历字典
# 遍历字典,字典以为大括号为标识符
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() #删除字典

 

阅读(1905) 评论(0)