python - Join lists by value -
is there efficient way merge 2 lists of tuples in python, based on common value. currently, i'm doing following:
name = [ (9, "john", "smith"), (11, "bob", "dobbs"), (14, "joe", "bloggs") ] occupation = [ (9, "builder"), (11, "baker"), (14, "candlestick maker") ] name_and_job = [] n in name: 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')] while code works fine small lists, it's incredibly slow longer lists millions of records. there more efficient way write this?
edit numbers in first column unique.
edit modified @john kugelman's code slightly. added get(), in case names dictionary doesn't have matching key in occupation dictionary:
>>>> names_and_jobs = {id: names[id] + (jobs.get(id),) id in names} >>>> print(names_and_jobs) {9: ('john', 'smith', none), 11: ('bob', 'dobbs', 'baker'), 14: ('joe', 'bloggs', 'candlestick maker')}
use dictionaries instead of flat lists.
names = { 9: ("john", "smith"), 11: ("bob", "dobbs"), 14: ("joe", "bloggs") } jobs = { 9: "builder", 11: "baker", 14: "candlestick maker" } if need convert them format, can do:
>>> {id: (first, last) id, first, last in name} {9: ('john', 'smith'), 11: ('bob', 'dobbs'), 14: ('joe', 'bloggs')} >>> {id: job id, job in occupation} {9: 'builder', 11: 'baker', 14: 'candlestick maker'} it'd piece of cake merge two.
names_and_jobs = {id: names[id] + (jobs[id],) id in names}
Comments
Post a Comment