首页 > 解决方案 > 从字典中检索键并改进此代码

问题描述

我正在设置自己的练习来提高我对 Python 的理解。我想创建一个程序来计算不同团队的投票份额。我首先将团队及其相应的票数放入字典中。

我可以先显示蓝队的投票份额,然后是红队等等,但我觉得我会一遍又一遍地重复相同的代码块。可以在这里使用函数吗?

还有一种方法可以从字典中检索密钥,而不必输入“蓝队”吗?

teams = {'blue' : 32224, 'red' : 16885, 'yellow' : 2302, 'green' :     965, 'others' : 482}
total = 52858
team_vote = teams.get('blue')
vote_share = team_vote / total_votes * 100
print(f'the blue team received {team_vote} votes')
print(f'That is a vote share of {vote_share} per cent')

标签: python

解决方案


尝试使用:

teams = {'blue' : 32224, 'red' : 16885, 'yellow' : 2302, 'green' :     965, 'others' : 482}
total = 52858
team_vote = teams.get('blue')
name = {v:k for k,v in teams.items()}.get(team_vote)
vote_share = team_vote / total_votes * 100
print(f'the {name} team received {team_vote} votes')
print(f'That is a vote share of {vote_share} per cent')

推荐阅读