here is my code:
#start.py
import json
y = {}
y['red'] = {'name': "red", 'p': 0, 'rand': 0}
y['blue'] = {'name': "blue", 'p': 0, 'rand': 0}
y['green'] = {'name': "green", 'p': 0, 'rand': 0}
with open('y.json', 'w') as f:
json.dump(y, f)
and
#main.py
import json
import random
f = open('y.json')
y = json.load(f)
for key, value in y.items():
y[key]['rand'] = random.randint(1, 101)
sorted_keys = sorted(y.keys(), key=lambda x: y[x]['rand'])
for i, key in enumerate(sorted_keys):
y[key]['p'] = i + 1
z = '%s%s%s' % (y['red']['name'], " ", y['red']['p'])
zz = '%s%s%s' % (y['blue']['name'], " ", y['blue']['p'])
zzz = '%s%s%s' % (y['green']['name'], " ", y['green']['p'])
print('\n'.join(sorted([z, zz, zzz], key=lambda x: int(x.split()[-1]), reverse=True)))
with open('y.json', 'w') as f:
json.dump(y, f)
I have it split, so I can first introduce the values to the JSON file and do everything else in the second.
What I wanna do with that program is basically generate a random number for (red, blue, green) and whoever has the highest number gets 3 points, second place get 2, third place gets 1.
And the output:
blue 3
red 2
green 1
For example, works just how I want it to work.
Now my problem is that when I run the program again I get (for example):
red 3
blue 2
green 1
as my output instead of:
blue: 5
red: 5
green: 2
So basically everytime I want to run the program I want the 'p' to add up instead of overwriting them again.
And no, I just run start.py ONCE to set the needed values, after that I only use main.py, so I shouldn't be overwriting with
y = {}
y['red'] = {'name': "red", 'p': 0, 'rand': 0}
y['blue'] = {'name': "blue", 'p': 0, 'rand': 0}
y['green'] = {'name': "green", 'p': 0, 'rand': 0}
Thank you :-)
Aucun commentaire:
Enregistrer un commentaire