0

I'm currently trying to cache much stuff on my web game. Its kinda a speedrun game, where you have specific sections and it saves each duration for a section in a dict.

So right now, i have a pretty long dict:

dict = [{'account_id': '10', 'Damage': 4874, 'duration': 50.020756483078},    
{'account_id': '10', 'Damage': 5920, 'duration': 20.020756483078},
{'account_id': '10', 'Damage': 2585, 'duration': 30.02078},
{'account_id': '4', 'Damage': 3145, 'duration': 21.020756483078},
{'account_id': '4', 'Damage': 4202, 'duration': 60.020756483078},
{'account_id': '4', 'Damage': 5252, 'duration': 66.020756483078}]

(Its much more, up to 10 sections for an account_id, but I just created an example to use for this question)

Then we need to assign those times to an account_id

enterDict = {}
for x in dict :
     enterDict[x["account_id"]] = x

But when I try to get the times from the cache, via

account_id = "4"
EnterInfo = enterDict[account_id]
print(EnterInfo)

It only returns one

{'Damage': 5252, 'account_id': '4', 'duration': 66.020756483078}

As an addition:

If we resolve this, is there a way I can give them an order? Since dicts are messing up everything.

So it should start from the lowest duration to the top one, since thats the right correct order.

So I could just use [0] for the lowest duration of 21 [1] for 60 and [2] for 66. I wouldnt mind if there is a new key : value with "order": "0", "order": "1" and "order":"2"

{'account_id': '4', 'Damage': 3145, 'duration': 21.020756483078},
{'account_id': '4', 'Damage': 4202, 'duration': 60.020756483078},
{'account_id': '4', 'Damage': 5252, 'duration': 66.020756483078}]
Fragkiller
  • 589
  • 2
  • 8
  • 21

1 Answers1

1

What you actually want to do is to create a list of dictionaries as a value behind your 'account_id' key. Now you're replacing with each addition the previous value for the key instead of adding (appending) to it.

See 1 for a example how to initialize lists within a dictionary.

See 2 for a example to order a lists of dicts on a certain value. However I could also suggest a Pandas Dataframe for this Job.

This could be a solution:

from collections import defaultdict
from operator import itemgetter

enterDict = defaultdict(list)
for item in dict:
     enterDict[item['account_id']].append(item)

sortDict = defaultdict(list)
for key_of_dict in enterDict:
    sorted_list = sorted(enterDict[key_of_dict], key=itemgetter('duration'))
    sortDict[key_of_dict] = sorted_list
Community
  • 1
  • 1