Jalanji
Jalanji

Reputation: 3

max with dictionaries python, same structure, different output?

the first structure:

dic = {'l':2, 'o':3, 'p':6}

for key in dic:
    total = [dic[key]]
print max(total)

the output is 6

second structure:

dic = {}
print 'Enter line of text'
line = input('')
words = line.split()
print 'Words', words
print 'Counting'
for word in words:
    dic[word] = dic.get(word,0) + 1
print 'Dictionary of your text', dic

for num in dic:
    total = [dic[num]]
print max(total)

output is 1 and mostly 1

Upvotes: 0

Views: 42

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123440

You are only ever putting the last value in your total list:

for key in dic:
    total = [dic[key]]

This rebinds total each time to a new list. This then depends on the order of the dictionary, which is dependent on the dictionary insertion and deletion history.

Just use max(dic.values()) if you want to know the maximum value.

If you must use a loop, then at least append the value to an existing list:

total = []
for key in dic:
    total.append(dic[key])

print(max(total))

Upvotes: 2

Related Questions