Search code examples
pythondictionarydel

More Pythonic Code for Dictionary Deletions


I have the following code that produces the result I'm after, but I feel like there is probably a more Pythonic way to do this. Is there a dict comprehension or other approach that's a better way to write this code? Thanks.

positions_list = [{'symbol': 'ARDX',
  'description': 'ARDELYX INC',
  'quantity': 18.0,
  'cost': 162.18,
  'market_value': 163.08},
 {'symbol': 'GCT',
  'description': 'GIGACLOUD TECHNOLOGY I FCLASS A',
  'quantity': 2.0,
  'cost': 51.4,
  'market_value': 51.24},
 {'symbol': 'IMPP',
  'description': 'IMPERIAL PETROLEUM INC F',
  'quantity': 90.0,
  'cost': 312.3,
  'market_value': 303.3},
 {'symbol': 'MREO',
  'description': 'MEREO BIOPHARMA GROUP FUNSPONSORED ADR 1 ADR REPS 5 ORD SHS',
  'quantity': 21.0,
  'cost': 82.32,
  'market_value': 82.32}]

d, m, c = 'description', 'market_value', 'cost'

for key in positions_list:
    if d in key:
        del key[d]
        del key[m]
        del key[c]

positions_list

Output

[{'symbol': 'ARDX', 'quantity': 18.0},{'symbol': 'GCT', 'quantity': 2.0},{'symbol': 'IMPP', 'quantity': 90.0},{'symbol': 'MREO', 'quantity': 21.0}]


Solution

  • You can do:

    to_delete = {"description", "market_value", "cost"}
    
    positions_list = [{k: d[k] for k in d.keys() - to_delete} for d in positions_list]
    print(positions_list)
    

    Prints:

    [
        {"quantity": 18.0, "symbol": "ARDX"},
        {"quantity": 2.0, "symbol": "GCT"},
        {"quantity": 90.0, "symbol": "IMPP"},
        {"quantity": 21.0, "symbol": "MREO"},
    ]