Iterate over OrderedDict in Python

Dejell picture Dejell · Jan 7, 2014 · Viewed 77k times · Source

I have the following OrderedDict:

OrderedDict([('r', 1), ('s', 1), ('a', 1), ('n', 1), ('y', 1)])

This actually presents a frequency of a letter in a word.

In the first step - I would take the last two elements to create a union tuple like this;

 pair1 = list.popitem()
    pair2 = list.popitem()
    merge_list = (pair1[0],pair2[0])
    new_pair = {}
    new_pair[merge_list] = str(pair1[1] + pair2[1])
    list.update(new_pair);

This created for me the following OrderedList:

OrderedDict([('r', 1), ('s', 1), ('a', 1), (('y', 'n'), '2')])

I would like now to iterate over the elements, each time taking the last three and deciding based on the lower sum of the values what is the union object.

For instance the above list will turn to;

OrderedDict([('r', 1), (('s', 'a'), '2'), (('y', 'n'), '2')])

but the above was:

OrderedDict([ ('r', 1), ('s', 2), ('a', 1), (('y', 'n'), '2')])

The result would be:

OrderedDict([('r', 1), ('s', 2), (('a','y', 'n'), '3')])

as I want the left ones to have the smaller value

I tried to do it myself but doesn't understand how to iterate from end to beginning over an OrderedDict.

How can I do it?

EDITED Answering the comment:

I get a dictionary of frequency of a letter in a sentence:

{ 's':1, 'a':1, 'n':1, 'y': 1}

and need to create a huffman tree from it.

for instance:

((s,a),(n,y))

I am using python 3.3

Answer

Zhongjun 'Mark' Jin picture Zhongjun 'Mark' Jin · Feb 19, 2016

Simple example

from collections import OrderedDict

d = OrderedDict()
d['a'] = 1
d['b'] = 2
d['c'] = 3

for key, value in d.items():
    print key, value

Output:

a 1
b 2
c 3