Is nested dict comprehension are possible in python ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Is nested dict comprehension are possible in python ?

{x: x**2 for x in (2, 4, 6)} This is an ordinary dict comprehension

4th Jun 2021, 11:26 AM
lisa
3 Answers
+ 2
lisa It is possible. Example: print({i:{j:j for j in range(i)} for i in range(10)})
4th Jun 2021, 11:35 AM
˜”*°•.˜”*°• Mohan 333 •°*”˜.•°*”˜
˜”*°•.˜”*°• Mohan 333 •°*”˜.•°*”˜ - avatar
0
Jan "Bill" Markus >>> matrix = [ ... [1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... ] >>> >>>#nested list comprehension >>> [[row[i] for row in matrix] for i in range(4)] [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] By using dict comprehension it should return {{1:1, 2:5, 3:9}, {4:2, 5:6, 6:10}, {7:3, 8:7, 9:11}, {10:4, 11:8,12:12}}
4th Jun 2021, 11:37 AM
lisa
0
""" lisa your expected return value is invalid, as either you expect a set of dict (wich is not possible as dict are not hashable) or a dict of dict, but you doesn't provide keys for outer dict ^^ """ # however, you could build a list of dict: matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], ] mdict = [ { c*len(matrix)+r: matrix[r][c] for r in range(len(matrix)) } for c in range(len(matrix[0])) ] print(mdict) # or even a list of list: matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], ] mlist = [ [ matrix[r][c] for r in range(len(matrix)) ] for c in range(len(matrix[0])) ] print(mlist)
4th Jun 2021, 2:49 PM
visph
visph - avatar