Appending a list of dicts as an element of another list (Python) -
i've 2 lists, in 1 store information of few celebrities, , list store awards information pertaining these actors.
the problem trying solve combine these 2 lists 1 award information becomes attribute list of awards. , yes simple achieve.
for actor in actor_info: award in award_list: if actor['personid'] == award['personid']: if not actor.get('awards', false): actor.update({'awards':[]}) actor['awards'].append(award)
but if observe code above, iterates len(actor_info) * len(award_list)
times not elegant solution. there other perspective problem, execution cycles less.
note:
to explain problem more clearly, i've described below data structure using. each element in actor_info , award_info list dictionary.
actor_info = [] d = {} d['personid'] = 1210 d['firstname'] = 'robert , jr' d['lastname'] = 'downey' d['birthplace'] = 'manhattan, ny' d1 = {} d1['personid'] = 2842 d1['firstname'] = 'brad' d1['lastname'] = 'pitt' d1['birthplace'] = 'shawnee, ok' d2 = {} d2['personid'] = 361 d2['fname'] = 'cate' d2['lname'] = 'blanchett' d2['birthplace'] = 'melbournce, victoria' d3 = {} d3['personid'] = 261 d3['fname'] = 'meg' d3['lname'] = 'ryan' d3['birthplace'] = 'melbournce, victoria' actor_info.append(d) actor_info.append(d1) actor_info.append(d2) actor_info.append(d3)
award information:
k = {} k['year'] = '1992' k['won'] = 'no' k['category'] = 'best actor' k['name'] = 'academy award' k['movie'] = 'chaplin' k['personid'] = 1210 k1 = {} k1['year'] = '2008' k1['won'] = 'no' k1['category'] = 'best actor' k1['name'] = 'academy award' k1['movie'] = 'tropic thunder' k1['personid'] = 1210 k2 = {} k2['year'] = '2008' k2['won'] = 'no' k2['category'] = 'best actor' k2['name'] = 'academy award' k2['movie'] = 'the curious case of benjamin button' k2['personid'] = 2842 k3 = {} k3['year'] = '1989' k3['won'] = 'yes' k3['category'] = 'best supporting actress' k3['name'] = 'academy award' k2['movie'] = 'aviator' k3['personid'] = 361 award_list = [] award_list.append(k) award_list.append(k1) award_list.append(k2) award_list.append(k3)
first off, should switch dictionaries collections.namedtuple
, allows access data plain attributes.
anyway, can avoid quadratic iteration making lookup table before hand.
idtoactor = {a['personid']:a in actor_info} award in award_list: actor = idtoactor[award['personid']] actor.setdefault('awards',[]).append(award)
Comments
Post a Comment