I want to create a dictionary using the position of elements in each list of lists. The order of each nested list is very important and must remain the same.
Original nested lists and desired dictionary keys:
L_original = [[1, 1, 3], [2, 3, 8]]
keys = ["POS1", "POS2", "POS3"]
Desired dictionary created from L_original
:
L_dictionary = {"POS1": [1, 2], "POS2": [1, 3], "POS3": [3, 8]}
The code I have so far fails the conditionals and ends on the else
statement for each iteration.
for i in L_original:
for key, value in enumerate(i):
if key == 0:
L_dictionary[keys[0]] = value
if key == 1:
L_dictionary[keys[1]] = value
if key == 2:
L_dictionary[keys[2]] = value
else:
print(f"Error in positional data processing...{key}: {value} in {i}")
CodePudding user response:
Use a list comprehension as you enumerate
L_dictionary = dict()
for i, k in enumerate(keys):
L_dictionary[k] = [x[i] for x in L_original]
Or simply
L_dictionary = {k: [x[i] for x in L_original] for i, k in enumerate(keys)}
CodePudding user response:
I believe there are more clean ways to solve this with some fancy python API, but one of the straightforward solutions might be the following:
For each key
from keys
we take those numbers from L_original
's nested arrays which have the same index as key
has, namely idx
L_original = [[1, 1, 3], [2, 3, 8]]
keys = ["POS1", "POS2", "POS3"]
L_dictionary = {}
for (idx, key) in enumerate(keys):
L_dictionary[key] = []
for items in L_original:
L_dictionary[key].append(items[idx])
Your code goes to else
, because this else
is related to the if key == 2
, not to the whole chain of if
s. So if the key
is, for example, 0
the flow goes to else
, because 0 != 2
. To fix this, the second and subsequent if
s should be replaced with elif
. This relates the else
to the whole chain:
if key == 0:
# only when key is 0
elif key == 1:
# only when key is 1
elif key == 2:
# only when key is 2
else:
# otherwise (not 0, not 1, not 2)
CodePudding user response:
L_original = [[1, 1, 3], [2, 3, 8]]
keys = ["POS1", "POS2", "POS3"]
b=[list(x) for x in zip(L_original[0], L_original[1])]
a={i:b[index] for index,i in enumerate(keys)}
First, I have just created a new list by zipping(see zip) index of first nested list to the same index of other nested list.
Output of b: [[1, 2], [1, 3], [3, 8]]
Then created a dictionary using index of keys
: index of b
list.
Output of a: {'POS1': [1, 2], 'POS2': [1, 3], 'POS3': [3, 8]}