Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

python - Item.get() if key can have multiple names

I need to get the value of key's in my dictionary. The thing is the dict keys can change according to sensors.

possible keys: light_missing, dark_missing, pixel_missing

So I want to loop over all records and always get the value of the 'missing' data.

How can I do this with:

item.get("missing")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Data

I suppose that you have a dictionary like this:

item = { 
'light_missing': 1, 
'dark_missing': 0, 
'pixel_missing': 0, 
'light': 0, 
'dark': 1, 
'pixel': 1 
}

Computation

And you want to filter it, getting only the objects with a key ending with 'missing', like this:

for key, value in item.items():
    if key.endswith('missing'):
        print(key, value)

Or, if you want your result as a list:

result = [(key, value) for key, value in item.items() if key.endswith('missing')]

Output

The output from this snippet is:

light_missing 1
dark_missing 0
pixel_missing 0

Or, if used the "list alternative";

[('light_missing', 1), ('dark_missing', 0), ('pixel_missing', 0)]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...