简体   繁体   中英

Python- How do I set a max number for a value in a dictionary?

Here's my Dictionary:

Health = {'John' : 100}

What i want to do, is I want to set the maximum number a value can be as 100. So, if I typed in:

Health['John'] += 10
print Health

When this prints, I want the value of 'John' to be 100, since the max number the value can be is 100. If the code was:

Health = {'John' : 90}

Health['John'] += 12
print Health

I would want this to print 'John' : 100, since the max value is 100. Get it? Thanks

You can create your own subclass of dict:

class Mydict(dict):
    def __setitem__(self, key, val):
        super(Mydict, self).__setitem__(key, min(val, 100))
...         
>>> d = Mydict({'john': 100})
>>> d['john'] += 12
>>> d
{'john': 100}
>>> d['foo'] = 90
>>> d
{'john': 100, 'foo': 90}
>>> d['foo'] += 12
>>> d
{'john': 100, 'foo': 100}

You could create a special dict for this:

class CappedDict(dict):
  def __init__(self, cap):
    self.cap = cap
  def __setitem__(self, key, value):
    dict.__setitem__(self, key, min(value, self.cap))

d = CappedDict(100)
print d
d['Harry'] = 90
print d
d['Harry'] += 20
print d

You can't do that with just a dictionary unless you subclass dict . I would get the same functionality by having a function implement the logic:

something along these lines:

def add_to_health_with_max(dict,key,value,max_value):
    added = value + dict[key]
    if added > max_value:
        age = max_value
    else:
        age = added
    dict[key] = age
    return age

now

health = {'John' : 60}
print add_to_dict(health,'John',12,100)
print add_to_dict(health,'John',120,100)
print health

returns:

72
100
{'John': 100}

Now you are still using plain old dicts.

You could make your own class which implements the behaviour as you describe it by overriding __setitem__ , __getattr__ or both (Ashwini Chaudhary details how you would do this very well), but I suspect that would be overkill and impair redability.

Whether to subclass dict or use a function

It is a reasonable question to ask what is the best thing to do - this approach (writing a function to add to your dicts in a specific way) or subclassing dict to give you a an object with the specific behaviour you want.

It is difficult to answer this outside of the context of your application, for a small application where this logic will be used very locally I would go with the above approach, if you required this functionality in many different places and wanted to pass these dicts around the OOP approaches suggested are probably more useful.

Here is an extremely easy way to do this:

def value(h):
if h > 100:
    return 100
return h

I set the max value to 100. If the number is 150, it will return 100.

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