Adding an element to the key's value in ordered dictionary
<p>I have an ordered dictionary:</p>

<pre><code>{'20140106': '82.1000000',
 '20140217': '77.0300000',
 '20140224': '69.6200000',
 '20140310': '46.3300000',
 '20140414': '49.3800000',
</code></pre>

<p>Keys are dates: yyyy-mm-dd and i want to store all values of one month in one key:</p>

<pre><code>{'20140106': '82.1000000',
 '20140217': ['77.0300000','69.6200000',]
 '20140310': '46.3300000',
 '20140414': '49.3800000',
</code></pre>

<p>I realized this not very beutiful solution:</p>

<pre><code>val = []   #list, where i put all values for an exact month
previus_key = list(collection.keys())[0]
val.append(collection.get(previus_key))

for key in list(collection.keys())[1:]:
    if (key[4:6]==previus_key[4:6]):    #if it's the same month
        val.append(list(collection.pop(key)))             #remember the value and delete an item
    else:
        collection.update({previus_key:val})   #that means, we jumped to another month, so lets update the values for previus month 
        previus_key = key            #now, start the same algorihtm for a new month.
    val = collection.get(previus_key)
</code></pre>

<p>But, i get an error:<code>'str' object has no attribute 'append'</code> for line 
<code>val.append(list(collection.pop(key)))</code>. I researched it, and came to conclusion, that it must not be here! Because, i append a list to a list! 
So, please, point to my mistake and give advice, how could i make the code more beutiful. Thanks!</p>

<p>Why not make use of <code>reduce</code> and <code>filter</code> function. <code>reduce</code> will apply a function to every item in the iterated object, and you can also specify the initial value for <code>reduce</code> </p>

<pre><code>from collections import OrderedDict

a = {'20140106': '82.1000000', '20140217': '77.0300000', '20140224': '69.6200000', '20140310': '46.3300000', '20140414': '49.3800000'}


def aggr(result, item):
    key = filter(lambda x: x[:6] == item[0][:6], result.keys())
    if not key:
        result[item[0]] = [item[1]]
    else:
        result[key[0]].append(item[1])
    return result


r = OrderedDict()
print reduce(aggr, a.items(), r)
</code></pre>

python list dictionary