简体   繁体   中英

How to only store 3 values for a key in a dictionary? Python

So I tried to only allow the program to store only last 3 scores(values) for each key(name) however I experienced a problem of the program only storing the 3 scores and then not updating the last 3 or the program appending more values then it should do.

The code I have so far:

    #appends values if a key already exists
    while tries < 3:
        d.setdefault(name, []).append(scores)
        tries = tries + 1

Though I could not fully understand your question, the concept that I derive from it is that, you want to store only the last three scores in the list. That is a simple task.

d.setdefault(name,[]).append(scores)
if len(d[name])>3:
    del d[name][0]

This code will check if the length of the list exceeds 3 for every addition. If it exceeds, then the first element (Which is added before the last three elements) is deleted

Use a collections.defaultdict + collections.deque with a max length set to 3:

from collections import deque,defaultdict

d = defaultdict(lambda: deque(maxlen=3))

Then d[name].append(score) , if the key does not exist the key/value will be created, if it does exist we will just append.

deleting an element from the start of a list is an inefficient solution.

Demo:

from random import randint

for _ in range(10):
    for name in range(4):
            d[name].append(randint(1,10))

print(d)
defaultdict(<function <lambda> at 0x7f06432906a8>, {0: deque([9, 1, 1], maxlen=3), 1: deque([5, 5, 8], maxlen=3), 2: deque([5, 1, 3], maxlen=3), 3: deque([10, 6, 10], maxlen=3)})

One good way for keeping the last N items in python is using deque with maxlen N, so in this case you can use defaultdict and deque functions from collections module.

example :

>>> from collections import defaultdict ,deque
>>> l=[1,2,3,4,5]
>>> d=defaultdict()
>>> d['q']=deque(maxlen=3)
>>> for i in l:
...    d['q'].append(i)
... 
>>> d
defaultdict(<type 'collections.deque'>, {'q': deque([3, 4, 5], maxlen=3)})
from collections import defaultdict  
d = defaultdict(lambda:[])
d[key].append(val)
d[key] = d[key][:3]


len(d[key])>2 or d[key].append(value) # one string solution

A slight variation on another answer in case you want to extend the list in the entry name

d.setdefault(name,[]).extend(scores)
if len(d[name])>3:
    del d[name][:-3]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM