【问题标题】:dictionary convert to list and sort causing error [python2.7]字典转换为列表并排序导致错误[python2.7]
【发布时间】:2016-10-18 14:42:24
【问题描述】:

我有一本这样的字典:

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

我想根据键对字典进行排序并生成如下内容:

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

我尝试了 hours = list(dict.items()) 并且效果很好,但是当我之前尝试过时

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

我明白了

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

似乎只记录了小时数的第一位,但我不知道为什么。当我计算给定字符串中字符的频率时,for 循环运行良好。有人可以帮我解释一下吗?非常感谢。

【问题讨论】:

  • 你不应该影响 dict 函数!!!

标签: python list python-2.7 dictionary


【解决方案1】:

我认为您只是在迭代字典键而不是键和值对。

看看这篇文章: Iterating over dictionaries using 'for' loops

如果更新如下,您的代码应该可以工作:

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

【讨论】:

  • 谢谢大卫!这很有帮助!
【解决方案2】:

你可以试试这样的:

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

输出是:

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

【讨论】:

  • 其实我更喜欢你的iteritems() 解决方案,而不是我的列表理解。
【解决方案3】:

你会想要使用iteritems

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

当然,您不应该使用名称“dict”——将其重命名为其他名称,因为它已经是 dict 类的名称。如果需要,您也可以使用 items() - 它占用更多空间并且速度稍快一些,但如果您使用少量数据,则无关紧要。

【讨论】:

    【解决方案4】:

    当您执行for ... in d 时,dict 只会遍历字典中的键,而不是值。您得到的不是hour, count 的元组,而是被拆分为first_character, second_character 的两个字符的字符串,并不是说问题的最后输出中的每一对实际上都是拆分为元组的键。

    【讨论】:

      【解决方案5】:

      使用dict.items() 遍历键和值。将其与列表推导相结合,以获得您想要的列表并最终对其进行排序。

      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)]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-17
        • 1970-01-01
        • 2020-08-24
        • 2017-04-23
        • 2021-10-13
        相关资源
        最近更新 更多