简体   繁体   中英

Replace list value in Python dictionary

I have the following dictionary. For objects that have the value ['FAIL', 'PASS'] , I'd like to replace it with 'PASS' only.

Dict = [('Main Menu-046', ['PASS']), ('Main Menu-047', ['FAIL']), ('Main Menu-044', ['FAIL', 'PASS']), ('Main Menu-045', ['PASS']), ('Main Menu-042', ['FAIL', 'PASS']), ('Main Menu-043', ['FAIL'])

I tried the following:

if "FAIL" in [x for v in Dict.values() for x in v]: ## if true
    Dict.values == "PASS"

If I understood your question correctly, you want to replace ['FAIL', 'PASS'] with ['PASS']

processed_list = [(x[0], ["PASS"] if "PASS" in x[1] else x[1]) for x in Dict]

Results in:

[('Main Menu-046', ['PASS']),
 ('Main Menu-047', ['FAIL']),
 ('Main Menu-044', ['PASS']),
 ('Main Menu-045', ['PASS']),
 ('Main Menu-042', ['PASS']),
 ('Main Menu-043', ['FAIL'])]

You don't use a dict but a list of pair (Main, [PASS/FAIL])

If you want a dictionary, you can create it by d = { key:value, key:value ... } or by d = dict() and add item by simply d['newkey'] = value

Plus, if you wish, you can apply default value like this :

from collections import defaultdict

d = defaultdict(lambda : defaultvalue)

When you'll have your dict, try a loop like:

for key in d.keys():
  if d[key] == 'FAIL': # or if 'FAIL' in d[key] if d[key] is a list like ['FAIL']
    d[key] = 'PASS' # or == ? why a boolean without condition or return ?

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