user14177720
user14177720

Reputation:

How to get the key in the dictionary startswith

I have the below dictionary

my = {
  "1": {
    "flag": 1,
    "Col1": "Val1",
    "Col2": "Val2",
    "output": "Out1",
    "id": 33,
    "Out1": "Cost"
  },
  "2": {
    "flag": 1,
    "Col1": "Val1",
    "Col2": "Val2",
    "output": "Out1",
    "id": 34,
    "Out1": "Rev"
  },
  "3": {
    "flag": 0,
    "Col1": "Val1",
    "Col2": "Val2",
    "output": "Out1",
    "Out1": "Rev"
  },
  "4": {
    "flag": 0,
    "Col1": "Val1",
    "Col2": "Val2",
    "output": "Out1",
    "Out1": "Cost"
  }
}

I would like to

I have written the following piece of code but that doesn't seem to give the expected result.

{ k: {v: {i:x for i, x in v.items() if i.startswith('Col'),v['output'] if flag=1}.values()} for k,v in my.items()}

Expected result

{
  "1": {
    "Col1": "Val1",
    "Col2": "Val2",
    "output": "Out1"
  },
  "2": {
    "Col1": "Val1",
    "Col2": "Val2",
    "output": "Out1"
  }
}

Upvotes: 0

Views: 145

Answers (2)

Swadhikar
Swadhikar

Reputation: 2210

import json
my = {
    "1": {
        "flag": 1,
        "Col1": "Val1",
        "Col2": "Val2",
        "output": "Out1",
        "id": 33,
        "Out1": "Cost"
    },
    "2": {
        "flag": 1,
        "Col1": "Val1",
        "Col2": "Val2",
        "output": "Out1",
        "id": 34,
        "Out1": "Rev"
    },
    "3": {
        "flag": 0,
        "Col1": "Val1",
        "Col2": "Val2",
        "output": "Out1",
        "Out1": "Rev"
    },
    "4": {
        "flag": 0,
        "Col1": "Val1",
        "Col2": "Val2",
        "output": "Out1",
        "Out1": "Cost"
    }
}

result = {k: {v: my[k][v] for v in my[k] if (v.startswith('Col') or v.startswith('output'))} for k in
      my if my[k]['flag']}

print(json.dumps(result, indent=1))

Or, if you prefer using regular expressions, consider using re.match(start_string, input_string). This will match for strings at the beginning.

import re

result = {k: {v: my[k][v] for v in my[k] if re.match('Col', v) or re.match('output', v)} for k in my if
      my[k]['flag']}

    

Result

{
 "1": {
  "Col1": "Val1",
  "Col2": "Val2",
  "output": "Out1"
 },
 "2": {
  "Col1": "Val1",
  "Col2": "Val2",
  "output": "Out1"
 }
}

Upvotes: 0

sushanth
sushanth

Reputation: 8302

Try this,

{k : {kk : vv for kk, vv in v.items() if kk.startswith('Col') or kk == 'output'} for k,v in my.items() if v['flag']}

{'1': {'Col1': 'Val1', 'Col2': 'Val2', 'output': 'Out1'},
 '2': {'Col1': 'Val1', 'Col2': 'Val2', 'output': 'Out1'}}

Upvotes: 2

Related Questions