比较字典和lis的键

2024-04-25 13:34:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数字列表(比如a)。例如:

A = [ 0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7]

列表的许多元素都有与之相关联的列表,我将结果以字典的形式存储。这个字典的键总是属于列表A的元素。例如

D = {0.5: [1, 2], 0.7: [1, 1], 0.3: [7, 4, 4], 0.6: [5]}

在本例中,元素0.50.70.30.6附有列表,这些元素作为字典D中的键

对于没有附加列表的元素(0.10.20.3),我想将它们附加到字典D(并为它们分配空列表)并创建一个新字典D\u 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]}

Tags: 元素列表new字典数字形式本例
3条回答

使用dict理解,迭代A中的值,使用D.get()D中查找它们,默认为[]。你知道吗

D_new = { x: D.get(x, []) for x in A }

您可以使用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

您还可以从D:

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]
# []

相关问题 更多 >