Reputation: 53
I've created a dictionary to upload it to an excel file afterwards, but it is horribly unfiltered. The main dictionary looks like this:
I've filled the dictionary by matching the product_x, product_n, etc in both key and value.
main_dict = {
"product_x_name_1L": "product_x_pic_1l",
"product_y_name_4L": "product_y_pic_4l",
"product_z_name_20L": "product_z_pic_20l",
"product_n_name_1L": "product_n_pic_4l",
"product_q_name_200L": "product_q_pic_20l",
"product_s_name_4L": "product_s_pic_200l"
}
Thing is, the product_n_name can only have a pic for 1l volume, product_q can only have a 200l volume, etc. (well, because these are the only pics that I have). That misplace happens because when the dictionary is generated, the key is matched with any suitable value based on name match, even if the volume parameter is actually wrong.
So I came up with another dictionary, that could serve as key to sort the dictionary and skip the incorrect values: (the Ls in keys are in capital letters)
checker_dict = {
"1L": "1l",
"4L": "4l",
"20L": "20l",
"200L": "200l"
}
However, I don't really know how to create the merge code without a ton of nested for loops that will eventually rewrite the values over and over.
I need to implement something like this:
final_dict = {}
for key, value in main_dict.items():
for check_key, check_value in checker_dict.items():
if checker_key in key corresponds with checker_value in value:
# I know there is no such syntax, but still, I want them to be
# checked every time for having both elements in original key
# and value
final_dict[key] = value
Upvotes: 0
Views: 128
Reputation: 1599
Actually there is no need to use the checker dict. As your data is well formated (the volume is at the end of the string. You can just access the volume of the key and the value lower case the string and check if they match. If so then add it to your final_dict
. Here are different of doing the same thing:
For loop :
final_dict = {}
for key, value in main_dict.items():
if value.split('_')[-1].lower() == key.split('_')[-1].lower():
final_dict[key] = value
List comprehension:
final = {k: v for k, v in main_dict.items() if v.split('_')[-1].lower() == k.split('_')[-1].lower()}
Filter:
dict(filter(lambda kv: extract_lower(kv[0]) == extract_lower(kv[1]), main_dict.items()))
Output:
{'product_x_name_1L': 'product_x_pic_1l',
'product_y_name_4L': 'product_y_pic_4l',
'product_z_name_20L': 'product_z_pic_20l'}
Upvotes: 1
Reputation: 306
That seems to be easier than you think:
main_dict = {
"product_x_name_1L": "product_x_pic_1l",
"product_y_name_4L": "product_y_pic_4l",
"product_z_name_20L": "product_z_pic_20l",
"product_n_name_1L": "product_n_pic_4l",
"product_q_name_200L": "product_q_pic_20l",
"product_s_name_4L": "product_s_pic_200l",
}
checker_dict = {
"1L": "1l",
"4L": "4l",
"20L": "20l",
"200L": "200l"
}
final_dict = {}
for key, value in main_dict.items():
if checker_dict[key.split('_')[-1]] == value.split('_')[-1]:
final_dict[key]=value
Upvotes: 0