Python 字典(Dictionary) 基本操作

字典(Dictionary)是一种可变容器模型,且可存储任意类型对象
字典的每个键值 key=>value 对用冒号 : 分割,每个键值对之间用逗号 , 分割,整个字典包括在花括号 {} 中 ,格式如下所示:
d = {key1 : value1, key2 : value2 }

dict = {'a': 1, 'b': 2, 'c': '3'}

打印整个字典

print dict
{'a': 1, 'c': '3', 'b': 2}

访问字典里面值

print dict['a']
1

修改字典

dict['c'] = 4 # 更新
dict['d'] = "d" # 添加

print dict
{'a': 1, 'c': 4, 'b': 2, 'd': 'd'}

删除字典元素

 del dict['a']  # 删除键是'a'的条目

 print dict 
{'c': 4, 'b': 2, 'd': 'd'}

dict.clear() # 清空字典所有条目
del dict # 删除字典

通过遍历keys()来获取所有的键

for k in dict.keys() :
    print(k , dict[k])

('a', 1)
('c', '3')
('b', 2)

返回字典所有的值

 
for v in dict.values():
    print(v)

1
3
2

使用元组作为dict的key

dict2 = {(20, 30):'good', 30:'bad'}
print(dict2)

字符串模板中使用key

temp = '教程是:%(name)s, 价格是:%(price)010.2f, 出版社是:%(publish)s'
book = {'name':'Python基础教程', 'price': 99, 'publish': 'C语言中文网'}
# 使用字典为字符串模板中的key传入值
print(temp % book)
book = {'name':'C语言小白变怪兽', 'price':159, 'publish': 'C语言中文网'}
# 使用字典为字符串模板中的key传入值
print(temp % book)


教程是:Python基础教程, 价格是:0000099.00, 出版社是:C语言中文网
教程是:C语言小白变怪兽, 价格是:0000159.00, 出版社是:C语言中文网

你可能感兴趣的:(Python 字典(Dictionary) 基本操作)