在Python中使用字典时,如何返回具有相同值的键?

时间:2018-07-12 10:19:12

标签: python dictionary

我是Python的新手和初学者,我正在努力学习python字典类的概念。我有一本字典,用测验分数映射学生的名字。我需要找到一种方法来返回具有相同考试分数的学生的任何实例。到目前为止,我有类似的东西,但是我无法继续进行下去。

def student_scores():
scores={'Shawn':95, 'Craig':74, 'William':96, 'Sara':84, 'Adam':91 'Harold':74, 'Nelson': 87}

我在课堂教科书中查找示例,但没有发现任何可以帮助我解决此问题的方法。

4 个答案:

答案 0 :(得分:3)

您可以尝试这样的事情:

from collections import defaultdict
scores={'Shawn':95, 'Craig':74, 'William':96, 'Sara':84, 'Adam':91, 'Harold':74, 'Nelson': 87}
dd = defaultdict(list)
for key, value in scores.items():
    dd[value].append(key)
for k,v in dd.items():
    print k,':',v

将其作为输出

96 : ['William']
74 : ['Harold', 'Craig']
84 : ['Sara']
87 : ['Nelson']
91 : ['Adam']
95 : ['Shawn']

答案 1 :(得分:1)

您可以从Python使用Counter模块:

from collections import Counter

scores={'Shawn':95,
        'Craig':74,
        'William':96,
        'Sara':84,
        'Adam':91,
        'Harold':74,
        'Nelson': 87}

c = Counter(scores.values())
out = [{k:v} for k,v in scores.items() if c[v] > 1]
print(out) 

输出:

[{'Harold': 74}, {'Craig': 74}]

答案 2 :(得分:0)

假设您只想按他们的分数对其进行分组,则可以按照以下步骤进行操作:

In [124]:the_same_scores = {} 
     ...:for k, v in scores.items():
     ...:     if v in the_same_scores:
     ...:         the_same_scores[v].append(k)
     ...:     else:
     ...:         the_same_scores[v] = [k]
     ...:         

In [125]: 

In [125]: the_same_scores
Out[125]: 
{74: ['Harold', 'Craig'],
 84: ['Sara'],
 87: ['Nelson'],
 91: ['Adam'],
 95: ['Shawn'],
 96: ['William']}

In [126]: 

您可能只关心那些得分相同的人,您可以这样做:

In [127]: care_about = [i for i in the_same_scores.values() if len(i) > 1]

In [128]: care_about
Out[128]: [['Harold', 'Craig']]

您还想知道他们获得了多少分,您可以通过以下方式做到这一点:

In [133]: care_about = {k: v for k, v in the_same_scores.items() if len(v) > 1}

In [134]: care_about
Out[134]: {74: ['Harold', 'Craig']}

答案 3 :(得分:0)

scores = {'Shawn': 95, 'Craig': 74, 'William': 96, 'Sara': 84, 'Adam': 91, 'Harold': 96, 'Nelson': 74}
names = []
marks = []
for key, value in scores.items():
    names.append(key)
    marks.append(value)


start = 0
for l in range(start, len(marks)):
    for b in range(l):
        if marks[l] == marks[b]:
            print('names: {} , {}'.format(names[l], names[b]))
            print('marks: {} '.format(marks[l]))

这将给出以下输出,我更改了测试字典

names: Harold , William
marks: 96 
names: Nelson , Craig
marks: 74