Search code examples
pythondictionarywriter

Python Overwrite Dictionary write to text file issue


In my last question Rewriting my scores text file to make sure it only has the Last 4 scores (python) I managed to get a dictionary to be printed out like this:

Adam 150 140 130 50

Dave 120 110 80 60

Jack 100 90 70 40

But I also wanted the dictionary to show the last 4 results in alphabetical order, as such:

Adam:150
Adam:140
Adam:130
Adam:50
Dave:120
Dave:110
Dave:80
Dave:60
Jack:100
Jack:90
Jack:70
Jack:40

I have tried to use for k, v in d.iteritems(): but that does not work either since there are 4 values to every key in one dictionary (4 scores to every 1 name).

What is the fix to this solution to get the dictionary to print out the list like the block of text above back into my text file (guess_scores.txt)?

The code that helps me write the scores into the text file is this, if you require it.

writer = open('Guess Scores.txt', 'wt')

for key, value in scores_guessed.items():       
    output = "{}:{}\n".format(key,','.join(map(str, scores_guessed[key])))
    writer.write(output)
writer.close()

But I can't use the 3rd line (output = ... ) because that writes the scores to the text file similar to the block of code right at the top. I did try to use the iteritems but that returned an error in the IDLE.

Thanks, Delbert.


Solution

  • >>> d={'Adam': [150 ,140, 130 ,50] ,'Dave': [120, 110 ,80 ,60] ,'Jack' :[100, 90, 70 ,40]}
    >>> for k,v in sorted(d.items()):
    ...    for item in v:
    ...      print str(k) + ":" + str(item)
    ... 
    Adam:150
    Adam:140
    Adam:130
    Adam:50
    Dave:120
    Dave:110
    Dave:80
    Dave:60
    Jack:100
    Jack:90
    Jack:70
    Jack:40
    

    And for write in file :

    with open('Guess Scores.txt', 'wt') as f :
          for k,v in sorted(d.items()):
              for item in v:
                     f.write(str(k) + ":" + str(item)+'\n')