Вы можете использовать append()
:
lst = [
{"data": ["string"], "type": "one"},
{"data": ["a string "], "type": "one"},
{"data": ["another string"], "type": "three"},
]
def count_chars(e):
return len(e)
for d in lst:
d["data"].append(count_chars(d["data"][0]))
print(lst)
# [{'data': ['string', 6], 'type': 'one'}, {'data': ['a string ', 9], 'type': 'one'}, {'data': ['another string', 14], 'type': 'three'}]
Если в списке больше строк, вы можете использовать extend()
и перестроить новый список:
lst = [
{"data": ["string", "hi"], "type": "one"},
{"data": ["a string "], "type": "one"},
{"data": ["another string"], "type": "three"},
]
def count_chars(e):
return len(e)
for d in lst:
newlst = []
for x in d["data"]:
newlst.extend([x, count_chars(x)])
d["data"] = newlst
print(lst)
# [{'data': ['string', 6, 'hi', 2], 'type': 'one'}, {'data': ['a string ', 9], 'type': 'one'}, {'data': ['another string', 14], 'type': 'three'}]
Примечание: Поскольку count_chars()
просто возвращает len()
, может быть проще просто вызвать len()
.