SkyThaKid
SkyThaKid

Reputation: 53

Easy way to compare random results and convert them into "points" on a JSON file in Python

Here is a simplified version of my code:

import json
import random

y = {}
y['red'] = {'name': "red", 'p': 0}
y['blue'] = {'name': "blue", 'p': 0}
y['green'] = {'name': "green", 'p': 0}

with open('y.json', 'w') as f:
    json.dump(y, f)

f = open('y.json')
y = json.load(f)

rr = random.randint(1, 101)
rb = random.randint(1, 101)
rg = random.randint(1, 101)

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)

The 'random'-commands currently have no use, but I want to compare these 3 so that the highest random number adds 3 to 'p', the second-highest 2 to 'p' and the lowest 1 to 'p'.

Example:

if rr = 22; rb = 66; rg = 44

then the output should be:

blue 3
green 2
red 1

So that the values of p in my JASON file are:

y['red'] = {'name': "red", 'p': 1}
y['blue'] = {'name': "blue", 'p': 3}
y['green'] = {'name': "green", 'p': 2}

I know that the JSON file would be overwritten everytime I run the program, but this is just a simplified version.

I also know that I could use if statements for that, but I kinda don't want to because I would have to chain a lot of them and that's just not really pretty and takes a lot of time if I want to add more "colors".

I tried my best to explain my problem, but if there are still any questions please ask me.

Thank you :-)

Upvotes: 1

Views: 37

Answers (2)

currand60
currand60

Reputation: 119

You can add another item to the dict and then sort the dict keys on that item.

Replace:

rr = random.randint(1, 101)
rb = random.randint(1, 101)
rg = random.randint(1, 101)

With:

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

Upvotes: 1

rdnobrega
rdnobrega

Reputation: 789

From what I understood, you want to sort the values and keep the color tags? You can build a structure like this:

z = [['red', 22], ['blue', 66], ['green', 44]]
z.sort(key = lambda x: x[-1])

and then change the values of p:

z = [(z[x][0],x+1) for x in range(len(z))]

The result should be:

[('red', 1), ('green', 2), ('blue', 3)]

Upvotes: 0

Related Questions