简体   繁体   English

比较字典与列表的键

[英]Compare keys of dictionary with list

I have a list of numbers (say, A). 我有一个数字列表(比方说,A)。 For example: 例如:

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

Many elements of the list A have lists associated with them and I store that result in the form of a dictionary. 列表A的许多元素具有与它们相关联的列表,并且我以字典的形式存储该结果。 The keys of this dictionary are always elements which belong to the list A. For example, 此字典的键始终是属于列表A的元素。例如,

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

In this example the elements 0.5 , 0.7 , 0.3 and 0.6 have lists attached with them and these elements serve as keys in the dictionary D. 在此示例中的元素0.5,0.7,0.30.6具有连接与他们的列表和这些元素作为字典中的D.键

For the elements of A that do not have lists attached with them ( viz 0.1 , 0.2 , 0.3 ), I want to attach them to the dictionary D (and assign empty lists to them) and create a new dictionary, D_new. 对于一个没有连接与他们列出的元素( 0.1,0.2,0.3),我想将它们连接到字典d(并指派空列表给他们),并创建一个新的字典,D_new。 For example, 例如,

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 }

You can also make a defaultdict from D: 您也可以从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]
# []

You may use dict.setdefault : 你可以使用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

Final value: 最终价值:

>>> D
{0.5: [1, 2], 0.1: [], 0.2: [], 0.3: [7, 4, 4], 0.6: [5], 0.4: [], 0.7: [1, 1]}

Note: It is not creating the new dict , instead modifying the existing dict. 注意:它不是创建新的dict ,而是修改现有的dict。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM