遍历字典(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确实新增了一对键-值对。

输入描述:

输出描述:

按题目描述进行输出即可(注意前后两个输出部分需以一个空行进行分隔)。

operators_dict={'<':'less than','==':'equal'}
print('Here is the original dict:')
for item in sorted(operators_dict):
    print("Operator {name1} means {name2}.".format(name1=item,name2=operators_dict[item]))
operators_dict.setdefault('>','greater than')
print()
print('The dict was changed to:')
for item in sorted(operators_dict):
    print("Operator {name1} means {name2}.".format(name1=item,name2=operators_dict[item]))
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python字典练习可以通过编写一个程序来实现统计句子中每个单词出现的次数。可以使用split()方法将句子分割成单词,并使用字典来存储每个单词及其出现的次数。以下是一个示例代码: ```python s = input('请输入句子:') word_dict = {} s_li = s.split() for item in s_li: if item not in word_dict: word_dict\[item\] = 1 else: word_dict\[item\] += 1 for word, count in word_dict.items(): print(word, count) ``` 这段代码首先使用split()方法将输入的句子分割成单词,并使用一个空字典`word_dict`来存储每个单词及其出现的次数。然后,通过遍历分割后的单词列表,如果单词不在字典的键中,则将单词作为键,初始值为1;如果单词已经在字典的键中,则将对应的值加1。最后,通过遍历字典的键和值,打印出每个单词及其出现的次数。 希望这个示例代码可以帮助你进行Python字典练习。如果还有其他问题,请随时提问。 #### 引用[.reference_title] - *1* *3* [Python字典巩固练习(随机生成银行卡号、重复数字统计、模拟轮盘抽奖游戏等)](https://blog.csdn.net/qq_41830712/article/details/88993823)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [python字典练习](https://blog.csdn.net/weixin_45775963/article/details/103636530)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值