为什么Python为OrderedDict添加键和函数?

时间:2013-11-16 19:19:20

标签: python lambda ordereddictionary

以下是我的计划的一部分:

print(str(alphabet) + " ")
alphabet = OrderedDict(alphabet, key=lambda x: x[0])
print(str(alphabet) + " ")

这是该部分终端的输出:

{' ': (57301, 0.16656008557492746), 'a': (23596, 0.06858783929121637), 'c': (8761, 0.025466098492555794), 'b': (5129, 0.014908756896281095), 'e': (32343, 0.0940132431851081), 'd': (9401, 0.027326423002912572), 'g': (6125, 0.01780388691552383), 'f': (5582, 0.016225517838768), 'i': (24438, 0.0710353287251545), 'h': (10526, 0.03059652468127409), 'k': (1985, 0.005769912739153436), 'j': (622, 0.001808002883502991), 'm': (9517, 0.027663606820414736), 'l': (12504, 0.0363460901210955), 'o': (20552, 0.05973967083883195), 'n': (19586, 0.05693174353101219), 'q': (840, 0.0024416759198432674), 'p': (8986, 0.0261201188282281), 's': (20204, 0.05872811938632545), 'r': (18284, 0.053147145855255123), 'u': (7068, 0.020544958811252637), 't': (26396, 0.07672675902402726), 'w': (3767, 0.010949753797678083), 'v': (3136, 0.0091155901007482), 'y': (3600, 0.010464325370756861), 'x': (3004, 0.008731898170487114), 'z': (773, 0.0022469231976652926)} 
OrderedDict([(' ', (57301, 0.16656008557492746)), ('a', (23596, 0.06858783929121637)), ('c', (8761, 0.025466098492555794)), ('b', (5129, 0.014908756896281095)), ('e', (32343, 0.0940132431851081)), ('d', (9401, 0.027326423002912572)), ('g', (6125, 0.01780388691552383)), ('f', (5582, 0.016225517838768)), ('i', (24438, 0.0710353287251545)), ('h', (10526, 0.03059652468127409)), ('k', (1985, 0.005769912739153436)), ('j', (622, 0.001808002883502991)), ('m', (9517, 0.027663606820414736)), ('l', (12504, 0.0363460901210955)), ('o', (20552, 0.05973967083883195)), ('n', (19586, 0.05693174353101219)), ('q', (840, 0.0024416759198432674)), ('p', (8986, 0.0261201188282281)), ('s', (20204, 0.05872811938632545)), ('r', (18284, 0.053147145855255123)), ('u', (7068, 0.020544958811252637)), ('t', (26396, 0.07672675902402726)), ('w', (3767, 0.010949753797678083)), ('v', (3136, 0.0091155901007482)), ('y', (3600, 0.010464325370756861)), ('x', (3004, 0.008731898170487114)), ('z', (773, 0.0022469231976652926)), ('key', <function <lambda> at 0x1619f30>)])

如果您想知道这是在计算文件中的所有字母。元组中的值是计数和发生此字母的概率。

为什么会添加'('key',位于0x1619f30&gt;)'?

2 个答案:

答案 0 :(得分:1)

您是否尝试确保字典按字母顺序排列?如果是这样,您需要在首次排序后将它们一次插入OrderedDict。以下代码将执行此操作。

# Extract keys from dictionary into list and sort them
keys = list(alphabet).sort()

# Now insert them into the new ordered dictionary.
d = OrderedDict() 
for k in keys:
    d[k] = alphabet[k]

如果你有Python 2.7+,你可以使用字典理解并一举完成整个事情:

d = {k: alphabet[k] for k in list(alphabet).sort()}

答案 1 :(得分:1)

OrderedDict不接受任何特殊的key参数,因此该参数只是作为普通键添加到dict中。

但是,从代码的外观来看,我猜你对OrderedDict有一个更为根本的误解。你看过the documentation吗?

  

有序词典就像常规词典一样,但他们记得订购项目的顺序

请注意我强调的内容。 OrderedDict中的“Ordered”并不意味着“已排序”。这些物品不以任何方式相互比较。它只会记住它们的添加顺序。