Friday, 23 February 2018

Python Shelve eg2....- Day 13


  • updating shelve
  •   
    import shelve
    # with shelve.open("D:/WORK/2018/February/23-02-2018-Friday/shelveeg3") as fruit:
    fruit = shelve.open("D:/WORK/2018/February/23-02-2018-Friday/shelveeg3")
    fruit['orange']='citrus fruit'
    fruit['apple']='good for health'
    fruit['lemon']='small fruit'
    fruit['papaya']='good for eye'
    
    print(fruit)
    print(fruit['lemon'])
    
    fruit['lemon']='Can Make Juice'
    
    print(fruit)
    print(fruit['lemon'])
    
    for i in fruit:
        print(i +" - " + fruit[i])
    print("="*40)
    
    # while True:
    #     var1 = input("enter any fruit key - ")
    #     if var1 =='quit':
    #         break
    #     # print(fruit.get(var1,'entered key doent exits'))
    #     if var1 in fruit:
    #         print(fruit[var1])
    #     else:
    #         print('entered key does not exits')
    
    #to get the shelve in sorted order
    shelvesortlist = list(fruit.keys())
    shelvesortlist.sort()
    print(shelvesortlist)
    print(fruit)
    for var2 in shelvesortlist:
        print(var2+" - "+fruit[var2])
    print (fruit.values())
    print (fruit.items())
    print (fruit.keys())
    fruit.close()
    
    
    #the below example is not prefect,but the thing is there is a concept of writeback and sync
    #related to shelve object,which can be used to update the shelve based on memory usage
    #the benefits of these will be know later i guess.
    
    
    import shelve
    
    blt = ["bread","bacon","lettuce"]
    egg = ["boiled egg","Milk"]
    butter = ["cheese","butter"]
    pasta = ["pasta","macroni"]
    
    with shelve.open("D:/WORK/2018/February/23-02-2018-Friday/shelveupdateeg4") as recipes:
        recipes["blt"]=blt
        recipes["egg"]=egg
        recipes["butter"]=butter
        recipes["pasta"]=pasta
        print(recipes)
    
        for var1 in recipes:
            print(var1,recipes[var1])
    
    #in the eg above if we want to update the items against any key in shelve,
    #if we use append method ,it wont update the shelve like check using the below code
        recipes["egg"].append("omlette")
        for var1 in recipes:
            print(var1,recipes[var1])
    #we can update it correcty by changing the list itself and reassigning to the shelve
        templist = ["boiled egg","Milk","omlette"]
        recipes["egg"]=templist
        for var1 in recipes:
            print(var1,recipes[var1])
    
    print("="*40)
    with shelve.open("D:/WORK/2018/February/23-02-2018-Friday/shelveupdateeg4") as recipes:
        for var1 in recipes:
            print(var1,recipes[var1])
    print('*'*40)