I've attached the problem statement in the image. I somehow managed to get the "similar" output in the form of a list because dictionary needs to have a "unique" key all the time. Here's my code:
l=[]
words=[a for a in 'aaabccdd']
for i in words:
l.append((i,words.count(i)))
h = list(set(l))
print(h)
output of my code is:
[('a', 3), ('d', 2), ('b', 1), ('c', 2)]
but I want it in the form of a dictionary like this :
{1:['b'], 2:['c', 'd'], 3:['a']}
where count(frequency) acts as a key to the dictionary and elements with common frequency comes in the form of a list as shown above.
CodePudding user response:
Since you want to go from
[('a', 3), ('d', 2), ('b', 1), ('c', 2)]
to
{1:['b'], 2:['c', 'd'], 3:['a']}
Here is the piece of code to achieve this:
from collections import defaultdict
d = defaultdict(list)
for word, count in h:
d[count].append(word)
print(d)
Or the full program:
from collections import defaultdict
l=[]
words=[a for a in 'aaabccdd']
for i in words:
l.append((i,words.count(i)))
h = list(set(l))
d = defaultdict(list)
for word, count in h:
d[count].append(word)
print(d)
if you are not allowed to use defaultdict
, you can use the following:
l=[]
words=[a for a in 'aaabccdd']
for i in words:
l.append((i,words.count(i)))
h = list(set(l))
d = {}
for word, count in h:
if count in d:
d[count].append(word)
else:
d[count] = [word]
print(d)
CodePudding user response:
from collections import Counter
new_dict = {}
for key,val in dict(Counter('aaabccdd')).items():
if val not in new_dict:
new_dict[val] = key
elif type(new_dict[val]) == list:
new_dict[val].append(key)
else:
new_dict[val] = [new_dict[val]] [key]
print (new_dict)
output:
{3: 'a', 1: 'b', 2: ['c', 'd']}