'update dictionnary through a list
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"
}
]
Solution 1:[1]
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'}]
Solution 2:[2]
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'}]
Solution 3:[3]
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.
Solution 4:[4]
You can have a one line solution
l = ['a','b','c']
d = []
d = d.append([{"type": type(val), "title": val, "value": "/"+val} for val in l])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | aberkb |
Solution 2 | Sunderam Dubey |
Solution 3 | Apo |
Solution 4 | Asfandyar Abbasi |