How to return the first highest value that is placed in a dictionary
<pre><code>dic = {}
count = 0
i = 0
str_in = str_in.replace(' ','')
while i &lt; len(str_in):
    count = str_in.count(str_in[i])
    dic[str_in[i]] = count
    i += 1
for key in dic:
    if key == max(dic, key=dic.get):
        return key
        break
</code></pre>

<p>The dictionary that is made in this program is</p>

<pre><code>{'i': 1, 'h': 2, 'j': 2, 'o': 2, 'n': 1, 's': 2}
</code></pre>

<p>from the input <code>'joshin josh'</code></p>

<p>I am pretty sure the dictionary's max value returns h because it is the first value in the dictionary with the highest value, even if tied.
I want it to return j because that is the first letter I put into the dictionary. It seems like the dictionary automatically sorts the letters alphabetically, which I also don't understand. I want this to work with any string and all tied letters, not just this particular string. Correct me if I am wrong on anything, I am a noob.</p>

<p>If you don't want to manually count, you could use Python's <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow"><code>Counter</code></a> to count letter occurrences, find the max, then return the first letter in your string that matches that count:</p>

<pre><code>from collections import Counter

string = 'joshin josh'
counts = Counter(string)
max_count = max(counts.values())
print(next(c for c in string if counts[c] == max_count))  # j
</code></pre>

<p><code>next(c for c in string if letter_counts[c] == max_count)</code> returns the first letter in the given string for which the count is the max count.</p>

<p><strong>A more optimal approach</strong>:</p>

<p>The previous approach would have you traverse the string in the worst case three times. For a one-pass approach, it would be most efficient to just keep track of the max count and letter corresponding to it as you iterate through the string:</p>

<pre><code>from collections import defaultdict

counts = defaultdict(int)
max_letter = None
max_count = 0
string = 'joshin josh'
for c in string:
    counts[c] += 1
    if counts[c] &gt; max_count:
        max_letter = c
        max_count = counts[c]

print(max_letter)  # j
</code></pre>

python string dictionary