简体   繁体   中英

how to check same key present in Python Dictionary

I have a function where it call another method and returns 3 values, I have to store that in a dict, when the same function is called back, I have to check the dict if the same value already stored in dict, if it is I have to return that, else load new set of values.

IDS = {}

def get_ids(id):
    if id in IDS:
        return IDS[id], IDS[name], IDS[salary]
    else:
        id, name, salary = load_ids(id)
        IDS['id'] = id
        IDS['name'] = name
        IDS['salary'] = salary
        return id, name, salary 

here I am replacing the first stored ids, but I have to add the new values with new ids, load_ids do some calculation and return some values

you can get that for free using functools.lru_cache :

from functools import lru_cache

@lru_cache(maxsize=512)
def get_ids(id, name, salary):
    id, name, salary = load_ids(id, name, salary)
    return id, name, salary

You could do something like this, if you want to continue on your example.

# Example
IDS = {1: {'name': 'Peter', 'salary': 200000}}


def get_ids(id):
    if id in IDS:
        return id, IDS[id]['name'], IDS[id]['salary']
    else:
        name, salary = load_ids(id)
        IDS[id] = {}
        IDS[id]['name'] = name
        IDS[id]['salary'] = salary
        return id, name, salary

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