Home > database >  loop over a nested dictionary to create a new one
loop over a nested dictionary to create a new one

Time:09-27

I've got a nested dictionary like that:

d={'a1': {'b': ['x', 1]}, 'a2': {'b1': ['x1', 2]}}

Expected result:

[
    {
        "measurements": "XXXXX",
        "tags": {
            "MPC": b,
            "host": a1
        },
        "time": "timexxxxx",
        "fields": {
            x: 1
        }
    },
    {
        "measurements": "XXXXX",
        "tags": {
            "MPC": b,
            "host": a2
        },
        "time": "timexxxxx",
        "fields": {
            x: 1
        }
    }
]

that is what I'm trying, however it's being overwritten

for k,v in d.items():
    metrics['measurements'] = "XXXXX"
    if isinstance(v,dict):
            for j,h in v.items():
                    metrics['tags'] = {'MPC':j,'host':k}
                    metrics['time'] = "timexxxxx"
                    for value in h:
                        metrics['fields'] = {j:h}

and I'm getting:

{'fields': {'b1': ['x1', 2]},
 'measurements': 'XXXXX',
 'tags': {'MPC': 'b1', 'host': 'a2'},
 'time': 'timexxxxx'}

Could you give me some pointers on how to deal with this?

Thanks

CodePudding user response:

see below

import pprint

d = {'a1': {'b': ['x', 1]}, 'a2': {'b1': ['x1', 2]}}
data = []
for k, v in d.items():
    entry = {"measurements": "XXXXX"}
    entry['tags'] = {'MPC': list(v.keys())[0],"host": k}
    entry["time"] =  "timexxxxx"
    values= list(v.values())
    entry["fields"] = {values[0][0]:values[0][1]}
    data.append(entry)
pprint.pprint(data)

output

[{'fields': {'x': 1},
  'measurements': 'XXXXX',
  'tags': {'MPC': 'b', 'host': 'a1'},
  'time': 'timexxxxx'},
 {'fields': {'x1': 2},
  'measurements': 'XXXXX',
  'tags': {'MPC': 'b1', 'host': 'a2'},
  'time': 'timexxxxx'}]

CodePudding user response:

This code can help you:

d={'a1': {'b': ['x', 1]}, 'a2': {'b1': ['x1', 2]}}


def convert(dictionary):
    return [
        {
            "measurements": "XXXXX",
            "tags": {
                "MPC": list(value.keys())[0],
                "host": key
            },
            "time": "timexxxxx",
            "fields": dict(value.values())
        } for key, value in dictionary.items()
    ]


print(convert(d))

Results in [{'measurements': 'XXXXX', 'tags': {'MPC': 'b', 'host': 'a1'}, 'time': 'timexxxxx', 'fields': {'x': 1}}, {'measurements': 'XXXXX', 'tags': {'MPC': 'b1', 'host': 'a2'}, 'time': 'timexxxxx', 'fields': {'x1': 2}}]

CodePudding user response:

You can do it like this

#Empty List
li=[]
#Add Items in list
for i in range(2):
    d = {}
    d["measurment"] = "XXXXX"
    d["tags"] = {1: "x"}
    d["time"] = "timexxx"
    d["field"] = {2: "y"}
    li.append(d)

#Print list elements
for i in li:
    for key, value in i.items():
        print(key, ":", value)
    print()
  • Related