Python 3.7 字典(dict)学习

Python 基础 2020-05-06 已阅 2734 次

Python中,字典(dict) 是一种内置的映射类型,也是惟一的;字典由键及其相应的值组成,这种键-值对称为项(item)。

字典基础

定义

dict1 = {} # 空字典

# python 是完全动态数据类型,同一个字典Value类型可以是多种的
dict2 = {'name': 'python3.7', 'age': 19, 'website': 'http://www.python.org'}
print(dict2) # {'name': 'python3.7', 'age': 19, 'website': 'http://www.python.org'}

获取项数(键-值对数)

length = len(dict2)
print(length) # 3

删除项

del dict2['website'] # 通过key删除项
# dict2.clear() # 删除掉所有项
print(dict2) # {'name': 'python3.7', 'age': 19}

添加项

dict2['website'] = 'http://www.python.org'
print(dict2) # {'name': 'python3.7', 'age': 19, 'website': 'http://www.python.org'}

修改值

dict2['website'] = 'http://python.org' # 通过key修改值
print(dict2) # {'name': 'python3.7', 'age': 19, 'website': 'http://python.org'}

获取值

website = dict2['website'] # 通过 key 获取值 
print(website) # http://python.org

获取所有 key

keys = dict2.keys()
print(keys) # dict_keys(['name', 'age', 'website'])

# 排序后获取到的是list
keys = sorted(dict2.keys()) 
print(keys) # ['age', 'name', 'website']

获取所有 value

values = dict2.values()
print(values) # dict_values(['python3.7', 19, 'http://python.org'])

字典升阶

判断 key 在字典中是否存在

if 'mykey' in dict2:
    print('字典中存在 `mykey`')

if 'mykey' not in dict2:
    print('字典中不存在 `mykey`')

遍历字典

# 遍历 key
for key in dict2:
    value = dict2[key]
    print(key, value)

# 遍历 value
for value in dict2.values():
    print(value)

将字符串格式设置功能用于字典

# format_map 会自动查找与参数名一样的key,并获取值
desc = 'python home is {website}'.format_map(dict2)
print(desc) # python home is http://python.org

desc = '{name} home is {website}'.format_map(dict2)
print(desc) # python3.7 home is http://python.org

本文由 Harvey 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

还不快抢沙发

添加新评论