AndrewPolukhin

Lists change simultaneously

Jul 2nd, 2020
545
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.19 KB | None | 0 0
  1. def change_several_books(self, start_list_dictionaries):
  2.         changed_list_dictionaries = start_list_dictionaries.copy()
  3.         shortest_dict = min(changed_list_dictionaries, key=len)
  4.         dict_for_change = shortest_dict.copy()
  5.         for key, value in dict_for_change.items():
  6.             if isinstance(value, dict):
  7.                 for desc, type_value in value.items():
  8.                     new_value = input(f"--------<{desc}>: ")
  9.                     if new_value in ["del", "<del>"]:
  10.                         dict_for_change[key] = "<del>"
  11.                     elif new_value == "":
  12.                         dict_for_change[key] = "<continue>"
  13.                     else:
  14.                         if isinstance(type_value, (str, int, dict)):
  15.                             changed_dictionary[key_in_initial_dict] = {desc: new_value}
  16.                         elif isinstance(type_value, list):
  17.                             try:
  18.                                 changed_dictionary[key_in_initial_dict] =\
  19.                                     {desc: json.loads(new_value)}
  20.                             except json.decoder.JSONDecodeError:
  21.                                 changed_dictionary[key_in_initial_dict] =\
  22.                                     {desc: [new_value]}
  23.            
  24.  
  25.         for dictionary in changed_list_dictionaries:
  26.             for initial_key in dictionary.copy().keys():
  27.                 for key_for_change, value_for_change in dict_for_change.items():
  28.                     if initial_key == key_for_change:
  29.                         if value_for_change == "<continue>":
  30.                             pass
  31.                         elif value_for_change == "<del>":
  32.                             del dictionary[initial_key]
  33.                         elif isinstance(value_for_change, dict):
  34.                             dictionary[initial_key] = value_for_change
  35.  
  36.         with open(self.full_path, 'r') as file:
  37.             file_contents = json.load(file)
  38.  
  39.         file_contents = [
  40.             element
  41.             for element in file_contents
  42.             if element not in start_list_dictionaries
  43.         ]
  44.         file_contents.extend(changed_list_dictionaries)
  45.  
  46.         with open(self.full_path, 'w') as file:
  47.             json.dump(file_contents, file)
  48.  
  49.         print("\nSuccess!")
Add Comment
Please, Sign In to add comment