0
Is nested dict comprehension are possible in python ?
{x: x**2 for x in (2, 4, 6)} This is an ordinary dict comprehension
3 Answers
+ 2
lisa
It is possible.
Example:
print({i:{j:j for j in range(i)} for i in range(10)})
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}}
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)