Home > Back-end >  update dictionnary through a list
update dictionnary through a list

Time:05-06

I have this problem in my dictionary I have this list :

l=['a','b','c']

so I'd like to append it in my list of dictionary

d=[{
        "type": "text",
        "title": "",
        "value": ""
    }]

but depending on the length of my first list it will create automatically another dictionary inside 'd'

My expected output:

d=[{
        "type": "text",
        "title": "a",
        "value": "/a"
    },
{
        "type": "text",
        "title": "b",
        "value": "/b"
    },
{
        "type": "text",
        "title": "c",
        "value": "/c"
    }

]

Thanks!!

CodePudding user response:

If you use python ≥ 3.9 you can use dictionary update (| operator) within a list comprehension:

out = [d[0]|{'title': x, 'value': f'/{x}'} for x in l]

output:

[{'type': 'text', 'title': 'a', 'value': '/a'},
 {'type': 'text', 'title': 'b', 'value': '/b'},
 {'type': 'text', 'title': 'c', 'value': '/c'}]

CodePudding user response:

If the keys are fixed you can create a dict item for each item of your list and append it to your initial list of dicts. Something like following will do it.

l=['a','b','c']
d=[{
        "type": "text",
        "title": "",
        "value": ""
  }]
for item in l:
    dict_item={"type": "text", "title": item, "value": f"/{item}"}
    d.append(dict_item)

output:

[{'type': 'text', 'title': '', 'value': ''},
 {'type': 'text', 'title': 'a', 'value': '/a'},
 {'type': 'text', 'title': 'b', 'value': '/b'},
 {'type': 'text', 'title': 'c', 'value': '/c'}]

CodePudding user response:

l=['a','b','c']
template = {
        "type": "text",
        "title": "",
        "value": ""
    }

d = []

for v in l:
    template["title"] = v
    template["value"] = "/"   v
    d.append(dict(template))

In fact, in the last line, you can't just append template because it would append as a reference. You have to create another dict from the template before appending it.

  • Related