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>I think the issue lies in the last line of your code. You do assign a string to the variable <code>var</code> there.</p>

<p><strong>EDIT : Here is a suggestion which stays close to your original code.</strong></p>

<pre><code>new_collection = {}
for key in collection:
    month = key[:6]
    if new_collection.get(month) != None:
        new_collection[month].append(collection[key])
    else:
        new_collection[month] = [collection[key]]
</code></pre>

<p>Three things :
1) Here the result is a new dictionary instead of the same instance, as I find it generally preferable.
2) The keys are only the year and the month, as the day is irrelevant.
3) All the values are lists, instead of a mix of strings and lists.</p>

python list dictionary