Trying create a function to read a file and add additional multiple items to it into an organized dictionary then return it without changing the original dictionary. Not sure if
As we discussed in the comments, your main problem is figuring out where to place the new painting in the list of an artist's paintings based on it's title.
It appears to me, that this is some kind of a homework question, since there is no reason for these constraints in a real world setting. Because of that I'm not going to give you the full solution, but point you in the right direction (at least I'll try to).
Your algorithm should look something like this:
Get a dictionary with the name of the artist as the key and a list of his paintings as values. Each painting consists of title
, year
, height
, width
, media
and country
.
Given a new set of artist
, title
, year
, height
, width
, media
and country
you retrieve the list of that artists work.
Now your problem is to find out where to add the new painting (if it doesn't already exist).
You loop through all paintings in the aforementioned list. For each entry you check if the title
of the new work should be inserted before the current title
using the compare_to
-function below. If yes (-1
) you insert it. If the result is 0
it is already in the list and you return the dictionary. If the result is 1
you move on to the next item of the list. If there are no more items you append it to the end.
This is the compare_to
function:
def compare_to(string_1, string_2):
"""
This functions returns -1 if string_1 should be inserted before string_2,
0 if the strings are the same (in which case it doesn't matter - or this
shouldn't happen) and 1 if string_1 is supposed to be inserted after
string_2.
"""
abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
if string_1 == string_2:
return 0
for i in range(min(len(string_1), len(string_2))):
if abc.index(string_1[i]) < abc.index(string_2[i]):
return -1
# The strings are not the same, the shorter one should come first
if len(string_2) > len(string_1):
return -1
return 1
I don't know how you'd like to handle numbers in the comparison, feel free to add them to the abc
variable.