Filter Dictionary 'like' string

Viewed 58

I am building a python script to a vendor API. I am getting the below return in my response body:

[
  {
    "ID": 3189,
    "DefID": 17,
    "Value": "Newspaper",
    "Name": null,
    "ForeignKey": 54245074
  },
  {
    "ID": 3190,
    "DefID": 17,
    "Value": "Newspaper",
    "Name": null,
    "ForeignKey": 604567819
  },
  {
    "ID": 3191,
    "DefID": 18,
    "Value": "TV",
    "Name": null,
    "ForeignKey": 1169994785
  },
  etc.

The type is originally <class bytes> and I have converted to <class str> by using

data_str = data_bytes.decode('utf-8')

I have then tried to convert this to a dictionary, but that doesn't work because of the format.

data_dict = json.loads(data_str)

How do I create a dictionary of ForeignKeys and their corresponding Value by filtering this by DefID?

Example:

#for defID = 17
data_dict17 = {54245074:"Newspaper", 604567819:"Newspaper"}

#for defID = 18
data_dict18 = {1169994785:"TV"}

Any help is appreciated!

2 Answers

Instead of having a lot of different variables, it would make sense to put them in a dictionary of their own:

from collections import defaultdict
data_dict = defaultdict(dict)

for d in json.loads(data_str):
    data_dict[d['DefID']][d['ForeignKey']] = d['Value']

Result:

>>> data_dict
defaultdict(<class 'dict'>, {17: {54245074: 'Newspaper', 604567819: 'Newspaper'}, 18: {1169994785: 'TV'}})

If you prefer a regular dict, you can use data_dict = dict(data_dict) at the end.

Looks like you need a groupby DefID

data = [
  {
    "ID": 3189,
    "DefID": 17,
    "Value": "Newspaper",
    "Name": None,
    "ForeignKey": 54245074
  },
  {
    "ID": 3190,
    "DefID": 17,
    "Value": "Newspaper",
    "Name": None,
    "ForeignKey": 604567819
  },
  {
    "ID": 3191,
    "DefID": 18,
    "Value": "TV",
    "Name": None,
    "ForeignKey": 1169994785
  }
]

res = {}
for i in data:
    res.setdefault(i['DefID'], dict()).update({i["ForeignKey"]: i['Value']})
    #OR
    #res.setdefault(i['DefID'], []).append({i["ForeignKey"]: i['Value']})

print(res[17])  # --> {54245074: 'Newspaper', 604567819: 'Newspaper'}
Related