python-04 字典

# 第四章 当索引行不通时
# 4.1 字典的用途
#4.2 创建字典和使用字典
from copy import deepcopy
phonebook = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
print(phonebook)
# 4.2.1 函数 dict
items = [('name', 'Gumby'), ('age', 42)]
d = dict(items)
print(d)

# 4.2.2 基本的字典操作
print(len(d)) # 求出d 的长度
print(d['age'])
d['age'] = 44 # 重新复制
print(d)
del d['age'] #del d[k] 删除k的项
print(d)
print('age' in d) # in 查找 键是否存在

x = {}
x[42] = [1, 2]
print(x)

# 4.2.3 将字符串格式设置功能用于字典
phonebook = {'Beth': '9102', 'Alice':'2341', 'Cecil': '3258'}
print(phonebook)
print('Cecil\'s phone number is {Cecil}'.format_map(phonebook))
print('Cecil\'s phone number is {}'.format(phonebook['Cecil']))

# 4.2.4
# 1 clear
phonebook.clear()
print(phonebook)

# 2.copy
x = {'username': 'admin', 'machines': ['foo', 'bar', 'baz']}
y = x.copy()
#y = x
y['username'] = '123'
# y['machines'].remove('bar') 函数可以影响到的
print(y)
print(x)

y1 = deepcopy(x)

y1['username'] = '1234'
y1['machines'].remove('bar') # 属性是影响不到的
print(y1)
print(x)

# 3.fromkeys 创建一个新字典
print({}.fromkeys(['name', 'age']))

# 4 get
d = {}
# print(d['name']) 字典中不存在 'name' 就会报错
print(d.get('name'))
print(d.get('name', 'N/A'))
print(d)
# 5 items 返回一个 包含所有字典项的列表
d = {'title': 'Python Web Site', 'url': 'http://www.python.org', 'spam': '0'}
t = d.items()
print(t)
# dict_items([('title', 'Python Web Site'), ('url', 'http://www.python.org'), ('spam', '0')])
# 返回一个字典视图
d['title'] = '123'
print(t)
# 6.keys
print(d.keys())

# 7 pop 方获取与指定键相关联的值,并将该键-值对从字典中删除
print(d.pop('title'))
print(d)

# 8 popitem 法popitem类似于list.pop 随机弹出一个字典项
print(d.popitem())
print(d)

# 9 setdefault 存在时直接赋值,不存在时,新增
d = {}
print(d.setdefault('name', 'N/A'))
print(d)

# update 字典更新另外一个字典
d = {1: '1',
2: '2'
}
x = {1:'11'}
d.update(x)
print(d)

# 11 values
d = {}
d[1] = 11
d[2] = 22
d[3] = 33
d[4] = 44
print(d.values())
print(d.keys())

猜你喜欢

转载自www.cnblogs.com/fuyouqiang/p/11844620.html