Is there an efficient way to merge two tuple lists in python based on a common value. I am currently doing the following:
name = [ (9, "John", "Smith"), (11, "Bob", "Dobbs"), (14, "Joe", "Bloggs") ] occupation = [ (9, "Builder"), (11, "Baker"), (14, "Candlestick Maker") ] name_and_job = [] for n in name: for o in occupation: if n[0] == o[0]: name_and_job.append( (n[0], n[1], n[2], o[1]) ) print(name_and_job)
returns:
[(9, 'John', 'Smith', 'Builder'), (11, 'Bob', 'Dobbs', 'Baker'), (14, 'Joe', 'Bloggs', 'Candlestick Maker')]
Although this code works fine for small lists, it is incredibly slow for longer lists with millions of entries. Is there a more efficient way to write this?
EDIT The numbers in the first column are unique.
EDIT Changed @John Kugelman code a bit. Added get (), just in case the dictionary of dictionaries does not have a suitable key in the occupation dictionary:
>>>> names_and_jobs = {id: names[id] + (jobs.get(id),) for id in names} >>>> print(names_and_jobs) {9: ('John', 'Smith', None), 11: ('Bob', 'Dobbs', 'Baker'), 14: ('Joe', 'Bloggs', 'Candlestick Maker')}