Search code examples
pythonpython-3.xpyramidmako

remove duplicate items in list


Current code:

mylist = [('x', 'Value1', 'Value2'), ('x', 'Value3', 'Value4')]

for item in mylist:
   item[0], item[1], item[2]

current for loop output:

x, Value1 : Value2, 
x, Value3 : Value4

wanted output:

x, "Value1 : Value2, Value3 : Value4"

(those are string colons which I render myself)

What is the best and correct way to do this?

(I'm rendering it in a .mako template)


Solution

  • You can use dictionaries for that, adding the first element as the key. Then add the last 2 items as an inner dictionary as key and value.

    mylist = [('x', 'Value1', 'Value2'), ('x', 'Value3', 'Value4'), ('y', 'vvvv', 'mmmm')]
    
    d = {}
    
    for item in mylist:
       d.setdefault(item[0], "")
       d[item[0]] += ", " if len(d[item[0]]) else ""
       d[item[0]] += "{}: {}".format(item[1], item[2])
    
    result = []
    for k, v in d.items():
        t = [k]
        t.append(v)
        result.append(tuple(t))
    
    print(result)
    

    It already give you the output you desire:

    [('y', 'vvvv: mmmm'), ('x', 'Value1: Value2, Value3: Value4')]