ConfusinglyCuriousTheThird - 3 years ago 44
Python Question

# create dict with keys from matrix rows in form {row:[col, value]}

Given a list of lists,

`matrix`
(row j and column k, element value) I can make a flattened list of the values with the list-comprehension:

``````matrix = [['00','01','02'],['10','11','12'],['20','21','22']]
list_1  = [value for (j,row) in enumerate(matrix) for (k,value) in enumerate(row)]
print(list_1)
#output: ['00', '01', '02', '10', '11', '12', '20', '21', '22']
``````

which mimics nested for-loop syntax:

``````list_2 = []
for (j,row) in enumerate(matrix):
for (k,value) in enumerate(row):
list_2.append(value)
``````

If I wanted a dictionary of for entries of form {j:[k,value]}, what is the equivalent dict comprehension syntax, and why doesn't using a curly braced equivalent work? e.g.:

``````list_3  = {j:[k,value] for (j,row) in enumerate(matrix) for (k,value) in enumerate(row)}

#expected output: {0:[0,'00'], 0:[1,'01'], 0:[2,'02']...}
#actual output: {0: [2, '02'], 1: [2, '12'], 2: [2, '22']}
``````

Theres nothing wrong with your code. Dict keys are meant to be unique and duplicate keys are not possible in Dictionaries, since the reference is the same key in the dict comprehension the data will be replaced as you can see in your actual output.You can use the code in this way

``````matrix = [['00','01','02'],['10','11','12'],['20','21','22']]
a_list  = {j:row for (j,row) in enumerate(matrix)}
for key,value in a_list.items():
new_list = {}
for i,j in enumerate(value):
new_list[i]=j
a_list[key] = new_list
a_list
``````

Output:

``````{0: {0: '00', 1: '01', 2: '02'},
1: {0: '10', 1: '11', 2: '12'},
2: {0: '20', 1: '21', 2: '22'}}
``````

or

``````matrix = [['00','01','02'],['10','11','12'],['20','21','22']]
a_list  = {j:row for (j,row) in enumerate(matrix)}
for key,value in a_list.items():
new_list = []
for i,j in enumerate(value):
new_list.append([i,j])
a_list[key] = new_list
a_list
``````

Output:

``````{0: [[0, '00'], [1, '01'], [2, '02']],
1: [[0, '10'], [1, '11'], [2, '12']],
2: [[0, '20'], [1, '21'], [2, '22']]}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download