Reputation: 21
I have a dictionary looking something like this:
d = {'f1': ['a','a','b','c'],
'f2': ['b','c','d'],
'f3': ['a','c','d']}
I want to get information about how many keys have a certain value. For example: a:2, b:1, c:3... (And if value was in one key more than once, count only first one). Is there a way to do it? Everything I found was about comparing two dictionaries, but here I have one. I searched a lot but I haven't found solution for case like this. Thank you in advance for your help!
Upvotes: 1
Views: 692
Reputation:
genMap
in your code, it will do the jobd = {
'f1': ['a', 'a', 'b', 'c'],
'f2': ['b', 'c', 'd'],
'f3': ['a', 'c', 'd']
}
def genMap(obj):
final_map = {}
for key in obj:
already_mapped = []
for value in d[key]:
if(value not in already_mapped):
already_mapped.append(value)
if(value not in final_map):
final_map[value] = 0
final_map[value] += 1
return final_map
result = genMap(d)
print(result)
Output
{
'a': 2,
'b': 2,
'c': 3,
'd': 2
}
Upvotes: 2
Reputation: 26005
Slow one liner:
>>> {k:sum(1 for l in d.values() if k in l) for k in set(sum(d.values(), []))}
{'a': 2, 'd': 2, 'b': 2, 'c': 3}
Upvotes: 3
Reputation: 1147
This may not be the best way but is this what you are looking for?
d = {'f1': ['a','a','b','c'],'f2': ['b','c','d'],'f3': ['a','c','d']}
certain_value = 'a'
counter = 0
for key, value in d.items():
if certain_value in value:
counter += 1
print("{0} has the {1} for {2} times.".format(key, certain_value, counter))
counter = 0
Upvotes: 2