I am trying to re-order and extend lists of dictionary values with the right position and fill them with zeros.
myDict = {
"col-1": ['a', 'b', 'c', 'd', 'e', 'f', 'g'],
"col-2": ['a', 'b', 'c', 'd', 'f', 'e']
}
The desired output should look like this:
myDict = {
"col-1": ['a', 'b', 'c', 'd', 'e', 'f', 'g'],
"col-2": ['a', 'b', 'c', 'd', 'e', 'f', '0'] # '0' is zero
}
Note that values of lists are with order 'a', 'b', 'c', 'd', 'e', 'f', 'g'
. The maximum list length in myDict.values()
is fixed to 7 and the minimum is 6. myDict
can have more than two elements.
I tried to use Python - extending and filling list with zeros to match another list but didn't know exactly how to make it work for my case.
CodePudding user response:
Assuming the maximum length is 7 and values are only single characters from "a" to "g"
myDict = {
"col-1": ['a', 'b', 'c', 'd', 'e', 'f', 'g'],
"col-2": ['a', 'b', 'c', 'd', 'e', 'f']
}
for key, value_list in myDict.items():
new_value_list = [0 for i in range(7)]
for value in value_list:
new_value_list[ord(value) - 97] = value
myDict[key] = new_value_list
print(myDict)
CodePudding user response:
This should cover the cases identified in the original post and the clarification comment. The approach is, for each key of the dict, to iterate over the set of valid letters, outputting that letter (if it exists in the dict value), or '0' (if it doesn't).
myDict = {
"col-1": ['a', 'b', 'c', 'd', 'e', 'f', 'g'],
"col-2": ['a', 'b', 'c', 'd', 'f', 'e'],
"col-3": ['a', 'c', 'f'],
"col-4": ['b', 'd']
}
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
for key, value in myDict.items():
myDict[key] = [(x if x in value else '0') for x in letters]
print(f"{key}: {myDict[key]}")
prints:
col-1: ['a', 'b', 'c', 'd', 'e', 'f', 'g']
col-2: ['a', 'b', 'c', 'd', 'e', 'f', '0']
col-3: ['a', '0', 'c', '0', '0', 'f', '0']
col-4: ['0', 'b', '0', 'd', '0', '0', '0']
CodePudding user response:
seems to me that you could do this with a for-while loop:
for key in myDict.keys():
myDict[key] = sorted(myDict[key])
while len(myDict[key])<len(myDict["column1"]):
myDict[key].append('0')