Search code examples
pythonlistindexingordereddictionary

How would I append/merge/pair values of the same index or key and ignore values that don't have a matching index or key?


I am trying to pair/merge list values from two lists of the same index or key-value pair together. If the value does not have a key then it should not pair and if it does have a key it should.

I've tried appending the values using their index, however, it returns an IndexError: list index out of range. I have paired them using their keys, but the output is not my desired output

list1 = [[0, 1], [1, 2], [3, 1]]
list2 = ["append", "values", "to", "one", "another"]

#my attempt at pairing the lists together 
merger = dict(zip(list1, list2))
print(merger)

#converted the first value of the values in list 1 to a key
getKey = {words[0]:words[1:] for words in list1}

#OrderedDict() method to append the two lists
newDict = OrderedDict()
for i, v in enumerate(list2): 
    newDict.setdefault(v, []).append(getKey[i])
print(newDict)

Outputs

>>> merger output: 
{'append': [0, 1], 'values': [1, 2], 'to':[3, 1]}

>>> expected merger output: 
{'append': [0, 1], 'values':[1, 2], 'one':[3, 1]}

>>> newDict output: 
    IndexError: list index out of range

>>> newDict expected output:
    OrderDict([('append', [[0,1]]), ('values', [[1,2]]), ('one', [[3,1]])]

What I am trying to achieve here is for list1 to append to list2 if and only if it matches the key, else it should not output anything.

I'm not sure how to solve this. Thanks in advance


Solution

  • If I understood correctly you could do:

    list1 = [[0, 1], [1, 2], [3, 1]]
    list2 = ["append", "values", "to", "one", "another"]
    
    # create lookup tables (index, values)
    lookup1 = {k : [k, v] for k, v in list1}
    lookup2 = {i : v for i, v in enumerate(list2)}
    
    merge = {lookup2[k] : v  for k, v in lookup1.items()}
    
    print(merge)
    

    Output

    {'append': [0, 1], 'one': [3, 1], 'values': [1, 2]}
    

    Note that this solution assumes that the first values of the sub-lists in list1 correspond to the indices.