Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over OrderedDict in Python

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

like image 410
Dejell Avatar asked Jan 07 '14 22:01

Dejell


People also ask

What is OrderedDict python?

Python's OrderedDict is a dict subclass that preserves the order in which key-value pairs, commonly known as items, are inserted into the dictionary. When you iterate over an OrderedDict object, items are traversed in the original order. If you update the value of an existing key, then the order remains unchanged.

How does python maintain insertion order?

Python OrderedDict is a dict subclass that maintains the items insertion order. When we iterate over an OrderedDict, items are returned in the order they were inserted. A regular dictionary doesn't track the insertion order. So when iterating over it, items are returned in an arbitrary order.


1 Answers

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 
like image 195
Zhongjun 'Mark' Jin Avatar answered Sep 22 '22 01:09

Zhongjun 'Mark' Jin