Vladislav Ladenkov Vladislav Ladenkov - 2 months ago 6
Python Question

Adding an element to the key's value in ordered dictionary

I have an ordered dictionary:

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


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

{'20140106': '82.1000000',
'20140217': ['77.0300000','69.6200000',]
'20140310': '46.3300000',
'20140414': '49.3800000',


I realized this not very beutiful solution:

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)


But, i get an error:
'str' object has no attribute 'append'
for line
val.append(list(collection.pop(key)))
. 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!

Answer

I think the issue lies in the last line of your code. You do assign a string to the variable var there.

EDIT : Here is a suggestion which stays close to your original 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]]

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.

Comments