我有一种 python 字典键值行和列,如下所示。我想要做的是我想在行索引 0 和列索引 0 处添加一个新字段“another_new_field”。
我使用dpath 库来执行此操作,在这里我尝试做的是
import dpath.util
import pprint
pp = pprint.PrettyPrinter(indent=2)
ext_rows = [ { 'row': [ { 'column': [ { 'col': [ {'class': 'bg-success text-white'},
{'field': ['text01']}]},
{ 'col': [ {'class': 'bg-info text-white'},
{'field': ['text1']}]},
{ 'col': [ {'class': 'bg-secondary text-white'},
{'field': ['text2']}]}]}]},
{ 'row': [ { 'column': [ { 'col': [ {'class': 'bg-primary text-white py-3'},
{'field': ['text3']}]},
{ 'col': [ {'size': 6},
{'class': 'bg-primary text-white py-3'},
{'field': ['text3']}]}]}]}]
# at row 0, col0 add new field 'another_new_field'
dpath.util.set(ext_rows, '[0]/row/*/column/0/col/*/field', ["another_new_field"])
pp.pprint(ext_rows)
# RESULT IN:
# [ { 'row': [ { 'column': [ { 'col': [ {'class': 'bg-success text-white'},
# {'field': ['another_new_field']}]},
# { 'col': [ {'class': 'bg-info text-white'},
# {'field': ['text1']}]},
# { 'col': [ {'class': 'bg-secondary text-white'},
# {'field': ['text2']}]}]}]},
# { 'row': [ { 'column': [ { 'col': [ {'class': 'bg-primary text-white py-3'},
# {'field': ['text3']}]},
# { 'col': [ {'size': 6},
# {'class': 'bg-primary text-white py-3'},
# {'field': ['text3']}]}]}]}]
如结果所示,它不会附加新字段,而是用新字段替换现有值。但我希望它是这样的:
[ { 'row': [ { 'column': [ { 'col': [ {'class': 'bg-success text-white'},
{'field': ['text01','another_new_field']}]},
{ 'col': [ {'class': 'bg-info text-white'},
{'field': ['text1']}]},
{ 'col': [ {'class': 'bg-secondary text-white'},
{'field': ['text2']}]}]}]},
{ 'row': [ { 'column': [ { 'col': [ {'class': 'bg-primary text-white py-3'},
{'field': ['text3']}]},
{ 'col': [ {'size': 6},
{'class': 'bg-primary text-white py-3'},
{'field': ['text3']}]}]}]}]
我怎样才能做到这一点?谢谢。