按键索引将键值插入到列表中的嵌套字典中

时间:2017-12-11 16:32:43

标签: python

包含嵌套词典的列表:

k = [{'width_min': 0, 'width_max': 300, 'height_min': 0, 'height_max': 65535},
    {'width_min': 301, 'width_max': 600, 'height_min': 0, 'height_max': 65535},
    {'width_min': 601, 'width_max': 65535, 'height_min': 0, 'height_max': 65535}]

关键地图:

keymap = {
    'width_min': 'minWidth',
    'width_max': 'maxWidth',
    'height_min': 'minHeight',
    'height_max': 'maxHeight',
}

尝试使用相同的词典创建新列表,但键名不同:

new_data = []
for i, x in enumerate(k):
    for k, v in x.items():
        new_data.insert(i, {keymap[k]: v})
print('---> new_data:', new_data)

打印:

new_data: [{'maxHeight': 65535}, {'maxHeight': 65535}, {'maxHeight': 65535}, 
{'minHeight': 0}, {'maxWidth': 65535}, {'minWidth': 601}, {'minHeight': 0},   
{'maxWidth': 600}, {'minWidth': 301}, {'minHeight': 0}, {'maxWidth': 300},   
{'minWidth': 0}]

如何通过索引更新嵌套字典而不是创建新字典? 期待数组:

k = [{'minWidth': 0, 'maxWidth': 300, 'minHeight': 0, 'maxHeight': 65535},
    {'minWidth': 301, 'maxWidth': 600, 'minHeight': 0, 'maxHeight': 65535},
    {'minWidth': 601, 'maxWidth': 65535, 'minHeight': 0, 'maxHeight': 65535}]

1 个答案:

答案 0 :(得分:4)

您可以遍历列表k并使用字典理解从keymap获取新的键名:

k = [{'width_min': 0, 'width_max': 300, 'height_min': 0, 'height_max': 65535},
{'width_min': 301, 'width_max': 600, 'height_min': 0, 'height_max': 65535},
{'width_min': 601, 'width_max': 65535, 'height_min': 0, 'height_max': 65535}]
keymap = {
'width_min': 'minWidth',
'width_max': 'maxWidth',
'height_min': 'minHeight',
'height_max': 'maxHeight',
}
k = [{keymap.get(a, a):b for a, b in i.items()} for i in k]

输出:

[{'minWidth': 0, 'maxHeight': 65535, 'minHeight': 0, 'maxWidth': 300}, {'minWidth': 301, 'maxHeight': 65535, 'minHeight': 0, 'maxWidth': 600}, {'minWidth': 601, 'maxHeight': 65535, 'minHeight': 0, 'maxWidth': 65535}]