Python - Compare items in a list of tuples

I have two lists of tuples (item name, version) - one that contains all the current items and the other contains the items to import. If there is a name clash between the imported and the current items, I want to revert to a newer version. My decision:

currentItemVersion = [("ItemA", "001"), ("ItemB", "002"), ("Camera", ""), ("SHD_metal", "001"), ("SHD_wood", "002")]
importItemVersion = [("ItemB", "001"), ("Camera", "001"), ("SHD_metal", "002"), ("SHD_wood", "004")]

def updateItems(currentItems, importItems):
    updatedItems = []
    for i, v in currentItemVersion:
        if i in [n[0] for n in importItemVersion]:
            ni, nv = importItemVersion[[n[0] for n in importItemVersion].index(i)]
            nvInt = int(nv) if nv else -1
            vInt = int(v) if v else -1
            if nvInt > vInt:
                updatedItems.append((ni, nv))
            elif nvInt == vInt:
                updatedItems.append((ni, nv))
            else:
                updatedItems.append((i, v))
        else:
            print('item {0} was not imported'.format(i))
            updatedItems.append((i, v))
    return updatedItems

print(updateItems(currentItemVersion, importItemVersion))

      

I am wondering if there is a better solution for this, especially on lines 7 and 8. Can I check somehow

if i in [n[0] for n in list]

      

and return n [1] in one operation?

+3


source to share


2 answers


You can use a dict and update items one at a time, checking the version of the one already in the dict if available, e.g .:

currentItemVersion = [("ItemA", "001"), ("ItemB", "002"), ("Camera", ""), ("SHD_metal", "001"), ("SHD_wood", "002")]
importItemVersion = [("ItemB", "001"), ("Camera", "001"), ("SHD_metal", "002"), ("SHD_wood", "004")]

def updateItems(currentItems, importItems):
    updated = {}
    for item, ver in currentItems + importItems:
        try:
            if int(ver) > int(updated.get(item, 0)):
                updated[item] = ver

        except ValueError:
            updated[item] = ver

    return updated

print updateItems(currentItemVersion, importItemVersion)

      

Output:

{'ItemB': '002', 'ItemA': '001', 'Camera': '001', 'SHD_wood': '004', 'SHD_metal': '002'}

      



dict.get(item, 0)

returns a version if the item is a valid key and 0

if not. You may want to print versions of versions before int()

before comparing.

Edit:

Added type int()

cast + try/except

to throw an exception when trying to cast ""

inint()

+1


source


Use a dict instead, this way you don't have to find the key conflict with the inner loop and reduce the complexity from O (m * n) to O (m).



+2


source







All Articles