Home > Back-end >  Python build dict from a mixture of dict keys and list values
Python build dict from a mixture of dict keys and list values

Time:08-18

Input body is:

{'columns': ['site_ref', 'site_name', 'region'], 'data': [['R005000003192', 'AIRTH DSR NS896876', 'WEST'], ['R005000003195', 'AIRTHREY DSR NS814971', 'WEST']]}

How could I build a new dict that will take the column values as keys and then populate a new dict for every list item within the data values for 1 to n?

Desired output would be:

{
  {
    "site_ref": "R005000003192",
    "site_name": "AIRTH DSR NS896876",
    "region": "WEST"
  },
{
    "site_ref": "R005000003195",
    "site_name": "AIRTH DSR NS896876",
    "region": "WEST"
  }
}

I have attempted to iterate over with:

for i in range(len(result["data"])):
    new_dict = []
    new_dict.append(dict(zip(result["columns"], result["data"][i])))

But cannot seem to get it to complete the iteration

CodePudding user response:

Note that you would require keys if the output should be a dictionary, which are currently missing in the provided desired output. However, you could create a list of dictionaries as follows:

d = {'columns': ['site_ref', 'site_name', 'region'], 'data': [['R005000003192', 'AIRTH DSR NS896876', 'WEST'], ['R005000003195', 'AIRTHREY DSR NS814971', 'WEST']]}
res = [{k: v for k, v in zip(d['columns'], datum)} for datum in d['data']]
print(res)

prints

[{'site_ref': 'R005000003192',
  'site_name': 'AIRTH DSR NS896876',
  'region': 'WEST'},
 {'site_ref': 'R005000003195',
  'site_name': 'AIRTHREY DSR NS814971',
  'region': 'WEST'}]

If you want keys after all, you could e.g. use the numbering (i.e. 1 for the first, n for the n-th datum) for the keys, as follows:

res = {i 1: {k: v for k, v in zip(d['columns'], datum)} for i, datum in enumerate(d['data'])}
print(res)

prints

{1: {'site_ref': 'R005000003192',
  'site_name': 'AIRTH DSR NS896876',
  'region': 'WEST'},
 2: {'site_ref': 'R005000003195',
  'site_name': 'AIRTHREY DSR NS814971',
  'region': 'WEST'}}
  • Related