Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Jun 2016
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Writing Dictionary values to a text file

    Hello all,

    I am currently writing information into a text file. However, one of the columns requires extracting dictionary values from the code below.

    for key,value in iDict.items():
    if value < 5:
    print("ID: ",key,"Current Stock Level: ",value,"This item urgently needs to be re-ordered")
    else:
    print("ID: ",key,"Current Stock Level: ",value)

    data = open("stock.txt", "r").readlines()
    output = ["%s\t%s %s %s" % (item.strip(), value, reorder, target) for item in data]
    f = open("orders.txt", "w")
    f.write("\n".join(output))
    f.close()

    When I print the values after the for loop, it displays the values fine. But when I want to transfer this to the text file, this happens:

    34512340 plain brackets 0.50 4 5 30
    98981236 product notfound 0.00 4 5 30
    56756777 100mm bolts 0.20 4 5 30
    90673412 L-shaped brackets 1.20 4 5 30

    The column with 4's are from the dictionary values and it appears to be only printing the last value within that for loop.

    Any advice?

    Thanks

    Dave

  2. #2
    New Coder
    Join Date
    Nov 2016
    Location
    South Africa, Cape Town
    Posts
    49
    Thanks
    1
    Thanked 1 Time in 1 Post
    Could you post the entire block of code? Or at least from the point where referenced variables are declared?


 

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •