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']}
2 Antworten
+ 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.
+ 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