python之字典操作

字典是python语言中唯一的映射类型.

# -*- coding: cp936 -*-
# dict examples

# 创建字典
dict1 = {}
dict2 = {'name':'earth', 'port':80}
fdict = dict((['x',1],['y',2]))

# 访问字典的值
# 1. 遍历
for key in dict2:
    print 'key=%s, value=%s' %(key, dict2[key])
# 2. 修改
dict2['name'] = 'moon'

# 检查是否存在对应的键
# 1. in
if 'name' in dict2:
    print dict2['name']
# 2. has_key()
if dict2.has_key('test') == True:
    print dict2['test']
else:
    print 'dict2 has not the value of \'test\''

# 增加元素
dict2['address'] = 'china'  # 若不存在对应key,则增加元素

# 删除元素
print dict2.pop('name')   #删除并返回键为'name'的条目
del dict2['address']
dict2.clear()   # 删除dict2中所有条目,dict2变成空字典
print dict2
del dict2       # 删除字典,字典不再存在

原文地址:https://www.cnblogs.com/wangzhijun/p/2956338.html