简体   繁体   English

从字典中检索键并改进此代码

[英]Retrieving a key from a dictionary and improving this code

I am setting myself exercises to improve my understanding of Python.我正在设置自己的练习来提高我对 Python 的理解。 I wanted to create a program that calculates vote share for different teams.我想创建一个程序来计算不同团队的投票份额。 I started by putting the teams and their corresponding numbers of votes into a dictionary.我首先将团队及其相应的票数放入字典中。

I could start by showing the vote share for blue team then red team and so forth, but I feel I would be repeating the same block of code over and over.我可以先显示蓝队的投票份额,然后是红队等等,但我觉得我会一遍又一遍地重复相同的代码块。 Can a function be used here instead?可以在这里使用 function 代替吗?

Also is there a way of retrieving a key from a dictionary instead of having to type out "the blue team"?还有一种方法可以从字典中检索密钥,而不必输入“蓝队”吗?

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')

Try using:尝试使用:

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')

The below code is as per your need.No need of function for this.下面的代码是根据您的需要。为此不需要 function。

teams = {'blue' : 32224, 'red' : 16885, 'yellow' : 2302, 'green' :965, 'others' : 482}
total = 52858
for i in teams.keys():
    team_vote = teams.get(i)
    vote_share = (team_vote / total) * 100
    print('The',i,'team received',teams[i],'votes')
    print('That is a vote share of',vote_share,'per cent')
    print("======")

maybe something like this:也许是这样的:

for key, value in teams.iteritems():
    if key == 'blue':
        print key

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM