0

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

4th Dec 2021, 1:43 PM
Msaligs
Msaligs - avatar
2 odpowiedzi
+ 1
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.
4th Dec 2021, 2:43 PM
Ipang
+ 1
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
4th Dec 2021, 2:46 PM
Msaligs
Msaligs - avatar