5、Python-字典

定义

info = {'name': '班长', 'id': 88, 'sex': 'man', 'address': '地球亚洲中国北京'}

print(info['name'])
print(info['address'])

# 若访问不存在的键,则会报错
# print(info['age'])
# 不确定字典中是否存在某个键而又想获取其值时,使用get方法,还可以设置默认值
print(info.get('age',22))

字典的操作

修改

info = {'name': '班长', 'id': 100, 'sex': 'f', 'address': '地球亚洲中国北京'}
info['id'] = int(150301016)
print('修改之后的id为:%d' % info['id'])

添加

info = {'name': '班长', 'sex': 'f', 'address': '地球亚洲中国北京'}
info['id'] = int(150301016)
print('添加之后的id为:%d' % info['id'])

删除

# 删除指定的元素
info = {'name': '班长', 'sex': 'f', 'address': '地球亚洲中国北京'}
del info['name']
info.get("name")

# 删除整个字典
info = {'name': 'monitor', 'sex': 'f', 'address': 'China'}
del info
print(info)
# NameError: name 'info' is not defined

# 清空整个字典
info = {'name': 'monitor', 'sex': 'f', 'address': 'China'}
info.clear()
print(info)
# {}

相关方法

info = {'name': 'monitor', 'sex': 'f', 'address': 'China'}

# 键值对的个数
print(len(info))
# 3

# 返回一个包含字典所有KEY的列表
print(info.keys())
# dict_keys(['name', 'sex', 'address'])

# 返回一个包含字典所有value的列表
print(info.values())
# dict_values(['monitor', 'f', 'China'])

# 返回一个包含所有(键,值)元组的列表
print(info.items())
# dict_items([('name', 'monitor'), ('sex', 'f'), ('address', 'China')])

# 如果key在字典中,返回True,否则返回False
print("x" in info)
# False

遍历

info = {'name': 'monitor', 'sex': 'f', 'address': 'China'}

# 遍历字典的key
for key in info.keys():
    print(key, end=" ")
# name sex address

# 遍历字典的value
for val in info.values():
    print(val, end=" ")
# monitor f China

# 遍历字典的元素
for item in info.items():
    print(item, end=" ")
# ('name', 'monitor') ('sex', 'f') ('address', 'China')

# 遍历字典的key-value
for key, val in info.items():
    print("k=%s,v=%s" % (key, val), end=" ")
# k=name,v=monitor k=sex,v=f k=address,v=China

其他遍历

# 带下标索引的遍历
chars = ['a', 'b', 'c', 'd']
i
= 0 for chr in chars: print("%d %s" % (i, chr)) i += 1
for i, chr in enumerate(chars): print(i, chr)
# 字符串遍历 a_str = "hello swt" for char in a_str: print(char, end=' ') # h e l l o s w t # 列表遍历 a_list = [1, 2, 3, 4, 5] for num in a_list: print(num, end=' ') # 1 2 3 4 5 # 元组遍历 a_turple = (1, 2, 3, 4, 5) for num in a_turple: print(num, end=" ") # 1 2 3 4 5

猜你喜欢

转载自www.cnblogs.com/jhxxb/p/10409107.html