Home > Software design >  How to update the values of a dictionary with a condition? [closed]
How to update the values of a dictionary with a condition? [closed]

Time:09-17

Supposing I have a dictionary,

 {'A1':[3, 2, 1],
 'A2': [9, 10, 11, 12, 13, 14],
 'B1': [4, 5, 6, 7, 8],
 'B2': [15]}

If I choose a number say 9, I want to update the values of all other keys, except A2 (since 9 belongs to key A2), with 'After' the last element of the key where the value was found, in this case 14.

EDIT: Another condition, when parsing through the dictionary if a given value is smaller than 9 we do not change its value.

Final dictionary,

 {'A1':[3, 2, 1],
 'A2': [9, 10, 11, 12, 13, 14],
 'B1': [4, 5, 6, 7, 8],
 'B2': ['After 14']}

CodePudding user response:

IIUC, assuming mutually exclusive values (i.e. values do not overlap):

n = 9
key, (*_, last)  = next((k, v) for k, v in d.items() if n in v)

{k: [f"After {last}"] if k != key else v for k, v in d.items()}

Output:

{'A1': ['After 14'],
 'A2': [9, 10, 11, 12, 13, 14],
 'B1': ['After 14'],
 'B2': ['After 14']}

CodePudding user response:

Suppose your dictionary is dct, try a dictionary comprhension:

x = next(v[-1] for k, v in dct.items() if 9 in v)
>>> {k: v if (9 in v) or all(x < 9 for x in v) else [f'After {x}'] for k, v in dct.items()}

{'A1': [3, 2, 1], 'A2': [9, 10, 11, 12, 13, 14], 
 'B1': [4, 5, 6, 7, 8], 'B2': ['After 14']}

Note this works for any value, not just 14.

CodePudding user response:

If the dictionary is defined as d, then

d['A1'] = item

will change the item assigned at 'A1'.

If you want automated algorithm then you can use:

for key in d:
    d[key] = item
  • Related