dictionary convert to list and sort causing error [python2.7]
<p>I have a dictionary which is a histogram of different hours in a day:</p>

<blockquote>
  <p>{'11': 6, '10': 3, '15': 2, '14': 1, '04': 3, '16': 4, '19': 1, '18':
  1, '09': 2, '17': 2, '06': 1, '07': 1}</p>
</blockquote>

<p>and I want to sort the dictionary based on the hours(first item) and produce something like:</p>

<blockquote>
  <p>('04', 3), ('06', 1), ('07', 1), ('09', 2), ('10', 3), ('11', 6),
  ('14', 1), ('15', 2), ('16', 4), ('17', 2), ('18', 1), ('19', 1)</p>
</blockquote>

<p>I tried hours = list(dict.items()) and it works pretty well, but when I tried earlier</p>

<pre><code>for hour, freq in dict:
    count = (hour, freq)
    lst.append(count)
lst.sort()
print lst
</code></pre>

<p>I get</p>

<blockquote>
  <p>('0', '4'), ('0', '6'), ('0', '7'), ('0', '9'), ('1', '0'), ('1',
  '1'), ('1', '4'), ('1', '5'), ('1', '6'), ('1', '7'), ('1', '8'),
  ('1', '9')</p>
</blockquote>

<p>It seems like only the first digit of the hours are recorded, but I don't know why. The for loop worked well when I was counting frequency of a character in a given string. Can somebody please help me explain this? Thanks a lot.</p>

<p>Go through both keys and values using <code>dict.items()</code>. Combine it with a list comprehension to get the list you want and finally sort it.</p>

<pre><code>a = {'11': 6, '10': 3, '15': 2, '14': 1, '04': 3, '16': 4, '19': 1, '18': 1, '09': 2, '17': 2, '06': 1, '07': 1}

b = sorted([(x, y) for x, y in a.items()])
print(b)
# prints
# [('04', 3), ('06', 1), ('07', 1), ('09', 2), ('10', 3), ('11', 6), ('14', 1), ('15', 2), ('16', 4), ('17', 2), ('18', 1), ('19', 1)]
</code></pre>

python list python-2.7 dictionary