[英]Replace values of dictionaries (in a list) with a value in list of lists
以下是我正在使用的字典列表(我故意保留了 2 个):
ld= [{'this': 1, 'is': 1, 'the': 1, 'first': 1, 'document': 1}, {'this': 1, 'document': 2, 'is': 1, 'the': 1, 'second': 1}]
以下是我的清单(我故意保留了 2 个):
b=[[0.2, 0.2, 0.2, 0.2, 0.2], [0.16666666666666666, 0.3333333333333333, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666]]
dict 键的计数为 10,b 中值的计数也是 10。我想用列表 ld 中具有相同索引值的 dict.values() 替换 b 中的值(即第一个 dict 中的“this”键应该获取 b) 中的第一个值。 我怎样才能完成这个任务?
这是一个快速,不优雅的解决方案:
ld= [{'this': 1, 'is': 1, 'the': 1, 'first': 1, 'document': 1}, {'this': 1, 'document': 2, 'is': 1, 'the': 1, 'second': 1}]
b=[[0.2, 0.2, 0.2, 0.2, 0.2], [0.16666666666666666, 0.3333333333333333, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666]]
for i, dictionary in enumerate(ld):
for j, key in enumerate(dictionary):
dictionary[key] = b[i][j]
print(ld)
我们遍历字典并索引它,这样我们就可以引用列表b
来提取相应的值。
以此为起点,我们现在可以使用列表理解编写更好的代码。
new_list = [{key: b[i][j]} for i, dictionary in enumerate(ld) for j, key in enumerate(dictionary)]
在这两种情况下,我们都得到了预期的输出:
>>> new_list
[{'this': 0.2}, {'is': 0.2}, {'document': 0.2}, {'the': 0.2}, {'first': 0.2}, {'this': 0.16666666666666666}, {'is': 0.3333333333333333}, {'document': 0.16666666666666666}, {'the': 0.16666666666666666}, {'second': 0.16666666666666666}]
我很乐意回答您可能有的任何其他问题。
编辑
@PacketLoss 正确地指出我的代码输出与错误混淆。 因此,我们可能会考虑使用collections.OrderedDict
的替代实现。 具体来说,
from collections import OrderedDict
for i, dictionary in enumerate(ld):
dictionary = OrderedDict(dictionary)
for j, key in enumerate(dictionary):
dictionary[key] = b[i][j]
这保持了原始字典的顺序完整性。
对于字典,不会保留键顺序(除非使用 Python 3.6+ )。 这意味着当您尝试利用列表项的索引将值设置为键的顺序时,您的数据可能并且将被设置为错误的键。
鉴于您评论说您有一个包含键名的辅助列表。 最好使用它来将数据和键的索引映射在一起,然后用这些值更新原始字典。
for indx, values in enumerate(b): # For index, and value in list
data = list(zip(values, klist[indx])) # Zip the elements in your list with the list located at the same index in klist
for row in data: # For tuple in [(0.2, 'this'), (0.2, 'is'), (0.2, 'the'), (0.2, 'first'), (0.2, 'document')]
ld[indx][row[1]] = row[0]
以上所有内容都会更新原始字典中的值,确保两个列表中的值都映射到正确的键,而不是随机顺序。
#[{'this': 0.2, 'is': 0.2, 'the': 0.2, 'first': 0.2, 'document': 0.2}, {'this': 0.16666666666666666, 'document': 0.3333333333333333, 'is': 0.16666666666666666, 'the': 0.16666666666666666, 'second': 0.16666666666666666}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.