Python – 字典列表中的值频率
给定两个字典列表,计算字典 1 到第二个中每个值对应的频率。
Input : test_list1 = [{“Gfg” : 6}, {“best” : 10}], test_list2 = [{“a” : 6}, {“b” : 10}, {“d” : 6}}]
Output : {‘Gfg’: 2, ‘best’: 1}
Explanation : 6 has 2 occurrence in 2nd list, 10 has 1.
Input : test_list1 = [{“Gfg” : 6}], test_list2 = [{“a” : 6}, {“b” : 6}, {“d” : 6}}]
Output : {‘Gfg’: 3}
Explanation : 6 has 3 occurrence in 2nd list.
方法:使用字典理解 + count() + 列表理解
上述功能的组合可以用来解决这个问题。在此,我们使用 2 个步骤执行此任务,首先我们从第二个列表中提取所有值,然后使用列表理解和 count() 与第一个字典执行频率映射。
Python3
# Python3 code to demonstrate working of
# Values frequency across Dictionaries lists
# Using list comprehension + dictionary comprehension + count()
# initializing lists
test_list1 = [{"Gfg" : 6}, {"is" : 9}, {"best" : 10}]
test_list2 = [{"a" : 6}, {"b" : 10}, {"c" : 9}, {"d" : 6}, {"e" : 9}, {"f" : 9}]
# printing original list
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# extracting values from target dictionary
temp = [val for sub in test_list2 for key, val in sub.items()]
# frequency mapping from 1st dictionary keys
res = {key : temp.count(val) for sub in test_list1 for key, val in sub.items()}
# printing result
print("The frequency dictionary : " + str(res))
输出
The original list 1 : [{'Gfg': 6}, {'is': 9}, {'best': 10}]
The original list 2 : [{'a': 6}, {'b': 10}, {'c': 9}, {'d': 6}, {'e': 9}, {'f': 9}]
The frequency dictionary : {'Gfg': 2, 'is': 3, 'best': 1}