python Save Dictionary and Read Dictionary Instance Code

  • 2021-07-10 20:03:39
  • OfStack

Read a saved dictionary


f = open('dict_th','r')
a = f.read()
dict_hi = eval(a)
f.close()

Save 1 dictionary


dict = {}
list1 = []
list2 = []
for line in lines:
  line = line.strip()
  if ">" in line:
    list1.append(line)
  else:
    list2.append(line)
for i in range():
  dict[list1[i]] = list2[i]
f6 = open("dict_th",'w')
f6.write(str(dict))
f6.close()

ps: Let's take a look at python using lists and dictionaries to store information


"""
   Author: Bai 
   Time: 2018 Year 1 Month 9 Day 
   Requirements: Suppose you have a lot of cars, and by constantly asking if you want to add vehicles to your inventory, 
   If you do, then it will ask for details of the car. If not, the application will print the details of all cars and exit. 
   Function: Cycle to add car-related information, and record the information to the dictionary 
"""
def main():
  car_list = []
  while True:
   add_inventory = input(' Do you want to add car information ? ( y/n ) :')
   if add_inventory == 'y':
    car_model = input(' Please enter the model of the car: ')
    car_color = input(' Please enter the color of the car: ')
    car_year = input(' Please enter the age of the car: ')
    car_miles = input(' Please enter the kilometers of the car: ')
    car_dict={'model':car_model,'color':car_color,'year':car_year,'miles':car_miles}
    print(car_dict)
    car_list.append(car_dict)
   elif add_inventory == 'n':
    print(car_list)
    break
if __name__ == '__main__':
  main()

Summarize

The above is the site to introduce you to save the python dictionary and read the example of the dictionary code, I hope to help you, if you have any questions welcome to leave me a message, this site will reply to you in time!


Related articles: