Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 按字典中元组的元素组织?_Python_Dictionary_Lambda - Fatal编程技术网

Python 按字典中元组的元素组织?

Python 按字典中元组的元素组织?,python,dictionary,lambda,Python,Dictionary,Lambda,我想用字典中的元组元素来组织 我正在编写一个组织元组元素的函数 grade = {'A+': 4.3, 'A': 4.0, 'A-': 3.7, 'B+': 3.3, 'B': 3.0, 'B-': 2.7, 'C+': 2.3, 'C': 2.0, 'C-': 1.7, 'D+': 1.3, 'D': 1.0, 'D-': 0.7, 'F' : 0.0} subject = {'math': {('Tom', 'A+'), ('Ke

我想用字典中的元组元素来组织

我正在编写一个组织元组元素的函数

grade = {'A+': 4.3, 'A': 4.0, 'A-': 3.7,
       'B+': 3.3, 'B': 3.0, 'B-': 2.7,
       'C+': 2.3, 'C': 2.0, 'C-': 1.7,
       'D+': 1.3, 'D': 1.0, 'D-': 0.7,
       'F' : 0.0}


subject = {'math':  {('Tom', 'A+'), ('Kevin','B+')},
       'History':  {('Kate', 'C+'),('Eric','C'),('Hannah','A-')}, 
       'English':  {('Eli', 'B-')}}`
我想要像这样的输出

{'A': {'math':{'Tom'}, 'history': {'Hannah'}}, 
  'B':{'math': {'Kevin'}, 'English': {'Eli'}}, 
  'C':{'History': {'Kate', 'Eric'}}}
我不知道如何删除后缀并按元素组织。。
我假设我需要几个字典和lambda,使用
集合。defaultdict

Ex:

from collections import defaultdict


subject = {'math':  {('Tom', 'A+'), ('Kevin','B+')},
       'History':  {('Kate', 'C+'),('Eric','C'),('Hannah','A-')}, 
       'English':  {('Eli', 'B-')}}

result = defaultdict(dict)
for k, v in subject.items():
    for name, grade in v:
        result[grade.rstrip("+-")].setdefault(k, set()).add(name)    #Use rstrip to strip + - 
print(result)
defaultdict(<class 'dict'>, {'A': {'math': {'Tom'}, 'History': {'Hannah'}}, 
                             'B': {'math': {'Kevin'}, 'English': {'Eli'}}, 
                             'C': {'History': {'Kate', 'Eric'}}
                             })
输出:

from collections import defaultdict


subject = {'math':  {('Tom', 'A+'), ('Kevin','B+')},
       'History':  {('Kate', 'C+'),('Eric','C'),('Hannah','A-')}, 
       'English':  {('Eli', 'B-')}}

result = defaultdict(dict)
for k, v in subject.items():
    for name, grade in v:
        result[grade.rstrip("+-")].setdefault(k, set()).add(name)    #Use rstrip to strip + - 
print(result)
defaultdict(<class 'dict'>, {'A': {'math': {'Tom'}, 'History': {'Hannah'}}, 
                             'B': {'math': {'Kevin'}, 'English': {'Eli'}}, 
                             'C': {'History': {'Kate', 'Eric'}}
                             })
defaultdict(,{'A':{'math':{'Tom'},'History':{'Hannah'},
'B':{'math':{'Kevin'},'English':{'Eli'},
‘C’:{‘历史’:{‘凯特’,‘埃里克’}
})

grade dict无论如何都不是很有用。