给出一个词典列表:
players= [
{ "name": 'matt', 'school': 'WSU', 'homestate': 'CT', 'position': 'RB' },
{ "name": 'jack', 'school': 'ASU', 'homestate': 'AL', 'position': 'QB' },
{ "name": 'john', 'school': 'WSU', 'homestate': 'MD', 'position': 'LB' },
{ "name": 'kevin', 'school': 'ALU', 'homestate': 'PA', 'position': 'LB' },
{ "name": 'brady', 'school': 'UM', 'homestate': 'CA', 'position': 'QB' },
]
如何通过匹配匹配的字典值将它们分组到组中,以便它喷出:
匹配值1:
名字:[亚特,约翰,凯文],
学校:[WSU,WSU,ALU],
homestate:[CT,MD,PA]
位置:[RB,LB,LB]
匹配值2:
姓名:[jack,brady],
学校:[ASU,UM],
homestate:[AL,CA]
职位:[QB,QB]
请注意,匹配值是任意的;也就是说,它可以在任何地方找到。也许是school
或position
,或两者兼而有之。
我尝试通过以下方式对它们进行分组:
from collections import defaultdict
result_dictionary = {}
for i in players:
for key, value in i.items():
result_dictionary.setdefault(key, []).append(value)
其中给出了:
{'name': ['matt', 'jack', 'john', 'kevin', 'brady'],
'school': ['WSU', 'ASU', 'WSU', 'ALU', 'UM'],
'homestate': ['CT', 'AL', 'MD', 'PA', 'CA'],
'position': ['RB', 'QB', 'LB', 'QB', 'QB']}
但是我仍然坚持如何进一步操作输出以匹配我上面提到的所需输出,并且我确信有更好,更简单的方法。
答案 0 :(得分:3)
只需使用您已导入的collections.defaultdict
:
In [21]: from collections import defaultdict
...: result = defaultdict(lambda: defaultdict(list))
...: for d in players:
...: for k,v in d.items():
...: result[d['school']][k].append(v)
...:
In [22]: result
Out[22]:
defaultdict(<function __main__.<lambda>>,
{'ASU': defaultdict(list,
{'homestate': ['AL'],
'name': ['jack'],
'position': ['QB'],
'school': ['ASU']}),
'WSU': defaultdict(list,
{'homestate': ['CT', 'MD'],
'name': ['matt', 'john'],
'position': ['RB', 'LB'],
'school': ['WSU', 'WSU']})})
答案 1 :(得分:1)
您可以找到最常见的标题值,并使用后一个值作为进一步分组的焦点:
import itertools
players= [
{ "name": 'matt', 'school': 'WSU', 'homestate': 'CT', 'position': 'RB' },
{ "name": 'jack', 'school': 'ASU', 'homestate': 'AL', 'position': 'QB' },
{ "name": 'john', 'school': 'WSU', 'homestate': 'MD', 'position': 'LB' },
{ "name": 'kevin', 'school': 'ALU', 'homestate': 'PA', 'position': 'S' },
{ "name": 'brady', 'school': 'UM', 'homestate': 'CA', 'position': 'QB' },
]
headers = ['name', 'school', 'homestate', 'position']
final_header = [[a, max(b, key=lambda x:b.count(x))] for a, b in zip(headers, zip(*[[i[b] for b in headers] for i in players])) if len(set(b)) < len(b)]
d = [[list(b) for _, b in itertools.groupby(filter(lambda x:x[i] == c, players), key=lambda x:x[i])][0] for i, c in final_header]
last_results = {'pattern {}'.format(i):{d[0][0]:[j[-1] for j in d] for c, d in zip(headers, zip(*map(dict.items, h)))} for i, h in enumerate(d, start=1)}
输出:
{'pattern 2':
{'homestate': ['AL', 'CA'],
'school': ['ASU', 'UM'],
'name': ['jack', 'brady'],
'position': ['QB', 'QB']},
'pattern 1':
{'homestate': ['CT', 'MD'],
'school': ['WSU', 'WSU'],
'name': ['matt', 'john'],
'position': ['RB', 'LB']}
}