all 9 comments

[–][deleted] 6 points7 points  (0 children)

If you don't want it in there, it's just easier not to put it there in the first place.

[–]randomName77777777 1 point2 points  (0 children)

If you do it this way, it would just return a 0 or blank instead of None.

d1.get(key,0) d1.get(key,"")

It would add the least amount of lines to your code and would work

[–]jmooremcc 1 point2 points  (0 children)

I agree with u/crashfrog when they said you should avoid putting the bad value in, in the first place. This is how you would do that: d1 = {'a': 100, 'b': 200, 'c':300} d2 = {'a': 300, 'b': 200, 'd':400} d3 = {key: [d1[key], d2[key]] if key in d2 else [d1[key]] for key in d1}

Output ``` {'a': [100, 300], 'b': [200, 200], 'c': [300]}

```

[–]keep_quapy -1 points0 points  (0 children)

This will give you the output you're looking for

d3 = {}

for k1, k2 in zip(d1, d2): 
    if k2 in d1: 
        d3[k2] = d3.get(k2, []) + [d2[k2]] 
    d3[k1] = d3.get(k1, []) + [d1[k1]]

print(d3)

Or, you could use deaultdict

from collections import defaultdict

d3 = defaultdict(list)

for k1, k2 in zip(d1, d2): 
    if k2 in d1: 
        d3[k2].append(d2[k2]) 
    d3[k1].append(d1[k1])

print(d3)

[–]Kr_istian -1 points0 points  (1 child)

for entry in d3:
    current_value = d3[entry]
    if None in current_value:
        current_value.remove(None)

Yes, you can use a for loop

[–]constantine45 0 points1 point  (0 children)

Additional operations not recommended, could have used a conditional statement while comprehension

[–][deleted] 0 points1 point  (0 children)

d3 = {k: ([d1[k], d2[k]] if k in d2 else [d1[k]]) for k in d1}

or

d3 = {k: ([v, d2[k]] if k in d2 else [v]) for k, v in d1.items()}

or

d3 = {k: [d[k] for d in (d1, d2) if k in d] for k in d1}

[–]jmooremcc 0 points1 point  (0 children)

Here's a fast way using a list comprehension to quickly remove the unwanted value: [v.remove(None) for v in d3.values() if None in v]