0

I have a dictionary like this:

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

and I want to sort the dictionary based on the key and produce something like:

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

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

for hour, freq in dict:
    count = (hour, freq)
    lst.append(count)
lst.sort()
print lst

I get

('0', '4'), ('0', '6'), ('0', '7'), ('0', '9'), ('1', '0'), ('1', '1'), ('1', '4'), ('1', '5'), ('1', '6'), ('1', '7'), ('1', '8'), ('1', '9')

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.

Xiaoyu Lu
  • 3,280
  • 1
  • 22
  • 34

5 Answers5

2

When you do for ... in d, the dict only iterates over the keys in the dictionary, not the values. Instead of getting a tuple of hour, count, you're getting a two-character string that's being split into first_character, second_character Not that each of the pairs in the last output of your question are actually the keys split into tuples.

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
2

You can try something like this:

d = {'11': 6, '10': 3, '15': 2, '14': 1, '04': 3, '16': 4, '19': 1, '18': 1, '09': 2, '17': 2, '06': 1, '07': 1}
l = list(d.iteritems())
l.sort()
print l

The output is:

[('04', 3), ('06', 1), ('07', 1), ('09', 2), ('10', 3), ('11', 6), ('14', 1), ('15', 2), ('16', 4), ('17', 2), ('18', 1), ('19',1)]
Gnukos
  • 115
  • 1
  • 6
2

You'll want to use iteritems

for hour, value in dict.iteritems():
    etc.

Of course, you shouldn't use the name 'dict' -- rename it to something else since it's already the name of the dict class. You can also use items() if you want -- it takes more space and is slightly faster but it shouldn't matter if you're using small amounts of data.

2

I think you are simply iterating over dictionary keys instead of pairs of key and value.

Have a look at this post: Iterating over dictionaries using 'for' loops

Your code should work if updated as below:

for hour, freq in dict.iteritems():
    count = (hour, freq)
    lst.append(count)
lst.sort()
Community
  • 1
  • 1
Dawid
  • 652
  • 1
  • 11
  • 24
1

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

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)]
Ma0
  • 15,057
  • 4
  • 35
  • 65