python - Combine two lists which have the same item in dict -
i have 2 lists named a_list
, b_list
:
a_list = [{'category_id': 1, 'category_name': u'aaa'}, \ { 'category_id': 2, 'category_name': u'bbb'}] b_list = [{'project_count': u'20', 'category_name': u'aaa'}, \ {'project_count': u'31', 'category_name': u'bbb'}]
i want make new list, c_list
, combines a_list
, b_list
category_name
. resulting list should like:
c_list = [{'category_id': 1,'project_count': u'20', 'category_name': u'aaa'},\ {'category_id': 2,'project_count': u'31', 'category_name': u'bbb'}]
the goal able access both page_max
, 'category_id' same 'category_name'.
for entry in c_list: page_num =1 category_name = entry['category_name'] category_id = entry['category_id'] url = 'https://www.test.com?category_id=%(category_id)s&page=%(page)s' % {'category_id': category_id, 'page': str(page_num)} print url # aaa project_count 20 # bbb project_count 31 page_max = int(entry['project_count']) in range(page_max - 1): page_num += 1 url = 'https://www.test.com?category_id=%(category_id)s&page=%(page)s' % {'category_id': category_id, 'page': str(page_num)} print url
how can merge dictionaries within lists based on value of key 'category_name'
?
you can create intermediate dictionary of {category_name: dict} , use update:
temp = {a['category_name']: dict(a) in a_list} b in b_list: temp[b['category_name']].update(b) c_list = list(temp.values()) # list() unnecessary in py2.x
but isn't guaranteed preserve order of lists. if order important:
c_list = [temp[a['category_name']] in a_list]
Comments
Post a Comment