我有一份字典列表,上面有我想在每本字典的钥匙下面替换的信息。
所以,我正在考虑遍历每个字典并替换这些值。
我有另一本字典,它包含我想要替换为键的值和作为值的值,它们应该是最后的值。
事情是这样的:
listOfDicts = [{'value_1' : 'A', 'value-2' : 'B', 'valu&_3' : 'C'}, {'value-1' : 'D', 'value_2' : 'E', 'value-3' : 'F'}, {'value_1' : 'G', 'value_2' : 'H', 'value_3' : 'I'}]然后,我有另一本词典可用作修复此信息的基础:
fixer = {'value-2' : 'value_2', 'value&_3' : 'value_3', 'value-3' : 'value_3', ...}我怎么才能更换这个呢?
想要的输出应该是这样的:
listOfDicts = [{
'value_1' : 'A',
'value_2' : 'B',
'value_3' : 'C'},
{'value_1' : 'D',
'value_2' : 'E',
'value_3' : 'F'},
...}发布于 2018-06-13 22:56:59
这应该适用于你:
listOfDicts = [{'value_1' : 'A', 'value-2' : 'B', 'value&_3' : 'C'}, {'value-1' : 'D', 'value_2' : 'E', 'value-3' : 'F'}, {'value_1' : 'G', 'value_2' : 'H', 'value_3' : 'I'}]
fixer = {'value-1' : 'value_1', 'value-2' : 'value_2', 'value&_3' : 'value_3', 'value-3' : 'value_3'}
for i in range(len(listOfDicts)):
keys = list(listOfDicts[i].keys())
temp_dict = dict()
for item in keys:
if item in fixer:
temp_dict[fixer[item]] = listOfDicts[i][item]
else:
temp_dict[item] = listOfDicts[i][item]
listOfDicts[i] = temp_dict
print(listOfDicts)输出
[{'value_1': 'A', 'value_2': 'B', 'value_3': 'C'}, {'value_1': 'D', 'value_2': 'E', 'value_3': 'F'}, {'value_1': 'G', 'value_2': 'H', 'value_3': 'I'}]
解释
这个程序所做的是遍历列表中的每一项,并在当前项的字典中获取键。然后,它创建一个临时字典(temp_dict),它将在其中存储固定的值。然后,程序遍历并查看是否需要修复任何键,如果需要,则根据fixer字典修复密钥。最后,它将在listOfDicts中迭代的项替换为固定值。
发布于 2018-06-13 22:55:56
我们可以用一个函数修复每一本字典:
fixer = {'value-2' : 'value_2', 'value&_3' : 'value_3', 'value-3' : 'value_3'}
def fix_dictionary(dict_):
return { fixer.get(k, k): v for k, v in dict_.items() }对于给定的dict_,这将构造一个新的字典,其中fixer中的键将被“固定”(由fixer字典中的相应值替换)。
然后,我们可以生成一个新的固定字典列表,其中包括:
[fix_dictionary(dict_) for dict_ in listOfDicts]或者我们可以消除这个功能,使用一个线性:
[{ fixer.get(k, k): v for k, v in dict_.items() } for dict_ in listOfDicts]发布于 2018-06-13 22:57:01
如果我没听错你想要这样的东西?
import json
import copy
listOfDicts = [
{
"valu&_3": "C",
"value-2": "B",
"value_1": "A"
},
{
"value-1": "D",
"value-3": "F",
"value_2": "E"
},
{
"value_1": "G",
"value_2": "H",
"value_3": "I"
}
]
fixer = {
"valu&_3": "value_3",
"value-2": "value_2",
"value-3": "value_3"
}
newDict = copy.deepcopy(listOfDicts)
for oldDct in newDict:
for k2, v2 in fixer.items():
value = oldDct.pop(k2, None)
if value:
oldDct[v2] = value
print('listOfDicts'.center(80, '-'))
print(json.dumps(listOfDicts, indent=4))
print('newDict'.center(80, '-'))
print(json.dumps(newDict, indent=4))输出:
----------------------------------listOfDicts-----------------------------------
[
{
"valu&_3": "C",
"value-2": "B",
"value_1": "A"
},
{
"value-1": "D",
"value-3": "F",
"value_2": "E"
},
{
"value_1": "G",
"value_2": "H",
"value_3": "I"
}
]
------------------------------------newDict-------------------------------------
[
{
"value_1": "A",
"value_3": "C",
"value_2": "B"
},
{
"value-1": "D",
"value_2": "E",
"value_3": "F"
},
{
"value_1": "G",
"value_2": "H",
"value_3": "I"
}
]https://stackoverflow.com/questions/50847329
复制相似问题