Commoner
Commoner

Reputation: 1768

Compare keys of dictionary with list

I have a list of numbers (say, 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. The keys of this dictionary are always elements which belong to the list A. For example,

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.

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. 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]}

Upvotes: 2

Views: 134

Answers (3)

akuiper
akuiper

Reputation: 214957

You can also make a defaultdict from 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]
# []

Upvotes: 3

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48077

You may use 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.

Upvotes: 2

shx2
shx2

Reputation: 64318

Use a dict-comprehension, iterating over values in A, looking them up in D using D.get(), defaulting to [].

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

Upvotes: 4

Related Questions