简体   繁体   中英

How can you find out which object a value belongs to?

Say I have a dictionary called dic:

dic = {"a":1, "b":2, "c":3}

And let's say I have some code, and later on, I provide the key dic["a"] to derive a value 1. How would I be able to inform the programme that the value 1 came from the key of "a" inside "dic", and not from say, a list, or another dic, and so on?

This is important because am writing a programme where there are many of the same values, but parts of the programme are going to run based upon where the value came from.

Thanks.

There is, as far as I know, no way to do what you're asking. Data retrieved from dictionaries and other sources have no knowledge of the key that they were associated with originally.

I think the cleanest method would be to have some kind of wrapper function that handles this for you and stores the data in an easy to use format:

from typing import Dict, NamedTuple

class Record(NamedTuple):
    amount: int
    source: str

def recording_get(dict: Dict[str, int], source: str) -> Record:
    return Record(dict[source], source)


dic = {"a":1, "b":2, "c":3}
rec = recording_get(dic, "a")
print(rec)  #  Prints Record(amount=1, source='a')

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