Search code examples
appendunique

Append and unique : Python


I am new to python and I want to append two lists in the following way:

list1=[2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2008, 2013, 2014]

list2=['Bahamas, The', 'Bahamas, The', 'Bahamas, The', 'Bahamas, The', 'Bahamas, The', 'Bahamas, The', 'Bahamas, The', 'Bahamas, The', 'Bahamas, The', 'Bahrain', 'Guyana', 'Guyana']

length of list 1 and list 2 are always equal in any condition.

I want the output to be :
2006: [’Bahamas, The’] 
2007: [’Bahamas, The’] 
2008: [’Bahamas, The’, ’Bahrain’] 
2009: [’Bahamas, The’] 
2010: [’Bahamas, The’] 
2011: [’Bahamas, The’] 
2012: [’Bahamas, The’] 
2013: [’Bahamas, The’, ’Guyana’] 
2014: [’Bahamas, The’, ’Guyana’]

Solution

  • I think the data structure you're looking for is a dictionary.

    Using this data structure, we can do the following.

    from collections import defaultdict
    

    Create a new defaultdict and pass it list.

    d = defaultdict(list)
    

    Next we need to zip the two lists. This can be done with:

    zip(list1, list2)
    

    If you're using Python 2, this will return a list (great, easy). However, if you're using Python 3, this produces a generator (see here). So, if you're using Python 3 (like me) to see what this thing looks like you can convert the generator to a list as follows:

    list(zip(list1, list2))
    

    Which is something like this:

    [(2006, 'Bahamas, The'), (2007, 'Bahamas, The'), (2008, 'Bahamas, The')...]
    

    Now all we have to do is iterate through this object as follows:

    for k, v in zip(list1, list2):
        d[k].append(v)
    

    So, all together:

    from collections import defaultdict
    
    d = defaultdict(list)
    for k, v in zip(list1, list2):
        d[k].append(v)
    

    To see the result you can use:

    for k, v in d.items(): # iteritems if Python 2
        print(k, v)
    

    This yields:

    2006 ['Bahamas, The']
    2007 ['Bahamas, The']
    2008 ['Bahamas, The', 'Bahrain']
    2009 ['Bahamas, The']
    2010 ['Bahamas, The']
    2011 ['Bahamas, The']
    2012 ['Bahamas, The']
    2013 ['Bahamas, The', 'Guyana']
    2014 ['Bahamas, The', 'Guyana']
    

    FYI.

    If you'd really like a list, and not a dictionary, you can use:

    list(d.items())     # Python 3
    
    list(d.iteritems()) # Python 2