[英]how to save output of tokenized string into list and compare that list with dictionary keys?
[英]Compare keys of dictionary with list
我有一个数字列表(比方说,A)。 例如:
A = [ 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]
列表A的许多元素具有与它们相关联的列表,并且我以字典的形式存储该结果。 此字典的键始终是属于列表A的元素。例如,
D = {0.5: [1, 2], 0.7: [1, 1], 0.3: [7, 4, 4], 0.6: [5]}
在此示例中的元素0.5,0.7,0.3和0.6具有连接与他们的列表和这些元素作为字典中的D.键
对于一个没有连接与他们列出的元素( 即 0.1,0.2,0.3),我想将它们连接到字典d(并指派空列表给他们),并创建一个新的字典,D_new。 例如,
D_new = {0.1: [], 0.2: [], 0.4: [], 0.5: [1, 2], 0.7: [1, 1],
0.3: [7, 4, 4], 0.6: [5]}
使用dict-comprehension,迭代A
值,使用D.get()
在D
查找它们,默认为[]
。
D_new = { x: D.get(x, []) for x in A }
您也可以从D创建一个defaultdict :
from collections import defaultdict
D_new = defaultdict(list, D)
# the key in D returns corresponding value
D_new[0.5]
# [1, 2]
# the key not in D returns empty list
D_new[0.2]
# []
你可以使用dict.setdefault
:
D = {0.5: [1, 2], 0.7: [1, 1], 0.3: [7, 4, 4], 0.6: [5]}
A = [ 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]
for a in A:
_ = D.setdefault(a, [])
# ^ add's empty list as value if `key` not found
最终价值:
>>> D
{0.5: [1, 2], 0.1: [], 0.2: [], 0.3: [7, 4, 4], 0.6: [5], 0.4: [], 0.7: [1, 1]}
注意:它不是创建新的dict
,而是修改现有的dict。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.