Search code examples
pythonfile-iopython-3.xeditdefaultdict

file IO with defaultdict


I'm attempting to:

  • load dictionary
  • update/change the dictionary
  • save
  • (repeat)

Problem: I want to work with just 1 dictionary (players_scores) but the defaultdict expression creates a completely seperate dictionary. How do I load, update, and save to one dictionary?

Code:

from collections import defaultdict#for manipulating dict
players_scores = defaultdict(dict)

import ast #module for removing string from dict once it's called back 


a = {}

open_file = open("scores", "w")
open_file.write(str(a))
open_file.close()

open_file2 = open("scores")
open_file2.readlines()
open_file2.seek(0)



i = input("Enter new player's name: ").upper()
players_scores[i]['GOLF'] = 0 
players_scores[i]['MON DEAL'] = 0
print()

scores_str = open_file2.read()
players_scores = ast.literal_eval(scores_str)
open_file2.close()
print(players_scores)

Solution

  • You are wiping your changes; instead of writing out your file, you read it anew and the result is used to replace your players_scores dictionary. Your defaultdict worked just fine before that, even if you can't really use defaultdict here (ast.literal_eval() does not support collections.defaultdict, only standard python literal dict notation).

    You can simplify your code by using the json module here:

    import json
    
    try:
        with open('scores', 'r') as f:
            player_scores = json.load(f)
    except IOError:
        # no such file, create an empty dictionary
        player_scores = {}
    
    name = input("Enter new player's name: ").upper()
    # create a complete, new dictionary
    players_scores[name] = {'GOLF': 0, 'MON DEAL': 0}
    
    
    with open('scores', 'w') as f:
        json.dump(player_scores, f)
    

    You don't need defaultdict here at all; you are only creating new dictionary for every player name anyway.