Ad

How To Write Two Else Condition In Dict Comprehension

- 1 answer

2 dictionary d1,d2, create a new dictionary with same keys.

d1 = {'product': '8', 'order': '8', 'tracking': '3'}
d2 = {'order': 1, 'product': 1,'customer':'5'}
dict3 = { k: [ d1[k], d2[k] ] if k in d2 else [d1[k]] for k in d1 }
dict3
{'product': ['8', 1], 'order': ['8', 1], 'tracking': ['3']}

How to pass else [d2[k]] for k in d2 to get the expected out

My Expected out

{'product': ['8', 1], 'order': ['8', 1], 'tracking': ['3'],'customer':['5']}

Disclaimer. I have done with defaultdict. Please give answer in dict comprehension only

Ad

Answer

You could use a nested ternary ... if ... else (... if ... else ...), but what if there are three dictionaries, or four? Better use a nested list comprehension and iterate over the different dictionaries.

>>> d1 = {'product': '8', 'order': '8', 'tracking': '3'}
>>> d2 = {'order': 1, 'product': 1,'customer':'5'}
>>> {k: [d[k] for d in (d1, d2) if k in d] for k in set(d1) | set(d2)}
{'customer': ['5'], 'order': ['8', 1], 'product': ['8', 1], 'tracking': ['3']}
Ad
source: stackoverflow.com
Ad