Reputation: 2641
I have this code
def query(q, L):
result = []
mDict = {}
key = 0
for x, i in enumerate(L):
for y in i:
if q == y:
key += 1
if q in i:
result.append(x)
mDict[key]=x
key = 0
print (mDict)
print (result)
q = "h"
l = ["phone", "power", "high", "phones"]
query(q, l)
I am expecting my printed output to be
{1: 0, 2: 2, 1: 3}
[0, 2, 3]
but instead I am getting
{1: 3, 2: 2}
[0, 2, 3]
can anyone help me out?
Upvotes: 0
Views: 101
Reputation: 2641
This code worked
q = "h"
L = ["phone", "power", "high", "phones"]
mDict = {}
values = 0
for x, i in enumerate(L):
for y in i:
if q == y:
values += 1
if q in i:
mDict[x]=values
values = 0
sorted_dict = sorted(mDict, key=mDict.get, reverse=True)
print (sorted_dict)
output
[2, 0, 3]
Upvotes: 0
Reputation: 122022
You don't need complex functions to count characters in Python, you can use str.count()
.
And to collate the counts, you can use collections.Counter
:
>>> from collections import Counter
>>> q = "h"
>>> l = ["phone", "power", "high", "phones"]
>>> Counter(word.count(q) for word in l)
Counter({1: 2, 0: 1, 2: 1})
Upvotes: 2