字典操作

# 字典 print('-----------字典的创建---------------\n') print('------------使用{}创建字典----------------') scores = {'张三': 100, '李四': 98, '王五': 45} print(scores) print('\n\n----------使用dict()函数创建-----------') student = dict(name='jack', age=20) print(student) # 空字典d d = {} print(d) print('\n\n\n\n\n--------字典元素获取------------') print('\n---------使用[]获取--------------') print(scores['张三']) # print(scores['mam'])#[]形式会在找不到对应元素时报错 print('----------使用get()方法-------------') print(scores.get('张三')) print(scores.get('mam'))  # get()函数找不到对应元素时返回None print(scores.get('mam', 99))  # 99是在查找'mam'对应的value不存在时,提供一个默认值 print('\n----------键的判断-------------') print('张三' in scores) print('张三' not in scores) print('\n----------字典的删除操作--------------') del scores['张三'# 删除key-value# scores.clear()#清空字典 print(scores) print('\n----------字典的新增操作--------------') scores['陈六'] = 98  # 新增元素 print(scores) print('\n----------字典的修改操作--------------') scores['陈六'] = 88 print(scores) print('----------获取字典视图-----------') scores = {'张三': 100, '李四': 98, '王五': 45} print('---------keys()获取字典所有的键-----------') keys = scores.keys() print(keys) print(list(keys))  # 将视图转为列表 print('\n---------values()获取字典所有的值-----------') values = scores.values() print(values) print(list(values)) print('\n---------items()获取字典所有的key-value-----------') items = scores.items() print(items) print(list(items))  # 转化之后的列表元素是由元组组成 print('\n\n----------字典元素遍历-----------') # 1.key for i in scores.keys():     print(i) # 2.value for i in scores.values():     print(i) # 3.所有项(元素)  item for i in scores.items():     print(i) # 4.依次打印keyvalue,通过索引 for key, value in scores.items():     print(key, value) # 5.元素值和对应的下标索引  enumerate(列表名) for i in enumerate(scores):     print(i) print('\n\n--------字典生成式---------') item = ['books', 'pen', 'paper'] price = [50, 554, 987, 45] d = {item: price for item, price in zip(item, price)} print(d) d = {item.upper(): price for item, price in zip(item, price)}  # upper()将其变为大写 print(d)

 

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务