E
E
Ellinium2014-05-06 12:59:57
Python
Ellinium, 2014-05-06 12:59:57

Adding data to a nested dictionary in Python

Hello, I have the following structure:

data = {
    "jsonrpc": "2.0",
    "method": "map.create",
    "params": {
        "name": "Hosts",
        "width": 500,
        "height": 500,
        "grid_show": 0,
        "label_type_host": 0,
        "label_type": 0,
        "selements": [
            {
              "elementid": "10327",
              "selementid": "1",
              "elementtype": 0,
              "iconid_off": "108",
              "label": "server-1",
              "x":200,
              "y":85,
            },
            {
              "elementid": "10084",
              "selementid": "2",
              "elementtype": 0,
              "iconid_off": "108",
              "label": "server-2",
              "x":400,
              "y":70,
            },
            # <= как добавить сюда элементы? :)
        ],
        "links": [
            {
                "selementid1": "1",
                "selementid2": "2"
            }
        ]
    },
    "auth": "asdasdasdasdasd",
    "id": 1
}

There is a task to add the data in the nested dictionary "selements" in a cycle. I can't figure it out. Please help. :)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
RokkerRuslan, 2014-05-06
@Ellinium

Let new_data be what you want to add

data = {
    "jsonrpc": "2.0",
    "method": "map.create",
    "params": {
        "name": "Hosts",
        "width": 500,
        "height": 500,
        "grid_show": 0,
        "label_type_host": 0,
        "label_type": 0,
        "selements": [
            {
              "elementid": "10327",
              "selementid": "1",
              "elementtype": 0,
              "iconid_off": "108",
              "label": "server-1",
              "x":200,
              "y":85,
            },
            {
              "elementid": "10084",
              "selementid": "2",
              "elementtype": 0,
              "iconid_off": "108",
              "label": "server-2",
              "x":400,
              "y":70,
            },
            # <= как добавить сюда элементы? :)
        ],
        "links": [
            {
                "selementid1": "1",
                "selementid2": "2"
            }
        ]
    },
    "auth": "asdasdasdasdasd",
    "id": 1
}

new_data = [ { "ha":1, "haha":2, "hahaha":3 },
             "string",
            42]

for item in new_data:
  data["params"]["selements"].append(item)

print(data)

V
v_prom, 2014-05-06
@v_prom

data["params"]["selements"][index] = value
or
data["params"]["selements"].append(value)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question