确定python中每个键中元素的频率

时间:2017-11-18 05:07:43

标签: python

我有一个字典列表如下。

mylist = [ {"0": ["code1", "code5"], "1" ["code8", "code7", "code2"]}, 
{"1": ["code2", "code3"], "2" ["code4", "code5", "code7"], "3": ["code1", "code10"]}, 
{"0": ["code8", "code5", "code1"], "2" ["code7", "code5", "code2"]} ]

现在,我想计算字典中每个键的代码数。例如,"0": ["code1", "code5"]"0": ["code8", "code5"]应该提供:mydict_for_0 = {"code1": 1, "code5": 2, "code8": 1}

因此,对于上述mylist,输出应为;

mydict_for_0 = {"code1": 2, "code5": 2, "code8": 1}
mydict_for_1 = {"code2": 2, "code3": 1, "code7": 1, "code8": 1}
mydict_for_2 = {"code4": 1, "code5": 2, "code7": 2, {"code2": 1}
mydict_for_3 = {"code1": 1, "code10": 1}

请使用python帮助我这样做!

2 个答案:

答案 0 :(得分:0)

这可能是解决方案

final_result = []
for i in mylist:
    current_list = mylist[i]
    d = {}
    for key in current_list:
        try:
            d[m]+=1
        except KeyError as e:
            d.update({m: 1})
        final_result.append(d)

for i in final_result:
    print(i)

答案 1 :(得分:0)

尝试使用defaultdict模块中的Countercollections,找到所有相同的键值列表,将它们扩展到一个列表中,保存到defaultdict(list)

from collections import defaultdict, Counter
new_dict = defaultdict(list)
for e in mylist:
    for key,value in e.items():
        new_dict[key].extend(value)

new_dict将是:

defaultdict(list,
            {'0': ['code1', 'code5', 'code8', 'code5', 'code1'],
             '1': ['code8', 'code7', 'code2', 'code2', 'code3'],
             '2': ['code4', 'code5', 'code7', 'code7', 'code5', 'code2'],
             '3': ['code1', 'code10']})

之后,循环所有项目以将值列表传递到Counter,以计算列表的出现次数:

result = {}
for key,value in new_dict.items():
    result['mydict_for_'+key] = dict(Counter(value))

result将是:

{'mydict_for_0': {'code1': 2, 'code5': 2, 'code8': 1},
 'mydict_for_1': {'code2': 2, 'code3': 1, 'code7': 1, 'code8': 1},
 'mydict_for_2': {'code2': 1, 'code4': 1, 'code5': 2, 'code7': 2},
 'mydict_for_3': {'code1': 1, 'code10': 1}}