天天看点

手把手带你学python—牛客网python基础 遍历字典

   牛客是一款不论是面试 还是刷题 都是非常有用的 还等什么,传送门- ​​牛客网python基础​​

🥇作者简介:大家好我是 uu 给刚入门的python的小伙伴带来一套python 完整的入门基础。

🥈个人主页:uu主页

📑 推荐一款非常火的面试、刷题神器👉  ​​牛客网python基础​​

觉得uu写的不错的话 麻烦动动小手 点赞👍 收藏⭐  评论📄

今天给大家带来的刷题系列是:  遍历字典

​​​ 

手把手带你学python—牛客网python基础 遍历字典

​​ 

手把手带你学python—牛客网python基础 遍历字典

题目介绍: 

描述

创建一个依次包含键-值对'<': 'less than'和'==': 'equal'的字典operators_dict,

先使用print()语句一行打印字符串'Here is the original dict:',

再使用for循环遍历 已使用sorted()函数按升序进行临时排序的包含字典operators_dict的所有键的列表,使用print()语句一行输出类似字符串'Operator < means less than.'的语句;

对字典operators_dict增加键-值对'>': 'greater than'后,

输出一个换行,再使用print()语句一行打印字符串'The dict was changed to:',

再次使用for循环遍历 已使用sorted()函数按升序进行临时排序的包含字典operators_dict的所有键的列表,使用print()语句一行输出类似字符串'Operator < means less than.'的语句,确认字典operators_dict确实新增了一对键-值对。

输入描述:

输出描述:

按题目描述进行输出即可(注意前后两个输出部分需以一个空行进行分隔)。
手把手带你学python—牛客网python基础 遍历字典

解题思路: 

operators_dict = {'<': 'less than','==': 'equal'}
 print('Here is the original dict:')
 for i in sorted(operators_dict.keys(),reverse=False):
     print('Operator %s means %s.'%(i,operators_dict.get(i)))
 operators_dict[">"]="greater than"
 print()
 print('The dict was changed to:')
 for i in sorted(operators_dict.keys(),reverse=False):
     print('Operator %s means %s.'%(i,operators_dict.get(i)))      

代码解析:

operators_dict = {'<': 'less than','==': 'equal'}
 print('Here is the original dict:')
 for i in sorted(operators_dict.keys(),reverse=False):
     print('Operator %s means %s.'%(i,operators_dict.get(i)))
 operators_dict[">"]="greater than"
 print()
 print('The dict was changed to:')
 for i in sorted(operators_dict.keys(),reverse=False):
     print('Operator %s means %s.'%(i,operators_dict.get(i)))