dict comprehension | Sololearn: Learn to code for FREE!


dict comprehension

Is their a way to redo the following code using dict comprehension l = ['abcd','bcd','fgh','azxs'] d= {} for x in l: if x[0] not in d: d[x[0]] = [x] else: d[x[0]].append(x) print(d) i tried the following way but it is throwing an error l = ['abcd','bcd','fgh','azxs'] A= {x[0]:[x] if x[0] not in A else x[0].append(x) for x in l} the expected output is dictionary : {'a': ['abcd', 'azxs'], 'b': ['bcd'], 'f': ['fgh']}

12/4/2021 1:43:50 PM


2 Answers

New Answer


I think your approach with for...loop is more suitable for such purpose. If I understood it correctly, comprehension is good for creating a dictionary item, or replacement of existing dictionary item's value. But here you rather want to add something to the item's value than to replace it with something else.


Ipang I was just exploring the list and dict comprehension , and curious to know whether this problem can be done by dictionary comprehension thanks for your reply