list - get keys value's from dictionary in python -
i have list of dictionary:
dictlist = [{'url': 'google.com', 'a': 10, 'content': 'google', 'd': 80, 'f': 1, 'lock': 'dd'}, {'url': 'fb.com', 'z': 25, 'content': 'google', 'd': 60, 'p': 1, 'a': 19}]
i need create new dictionary above dictlist
.
newdict= {} sumlist = ['a', 'z', 'd'] #get values these dictlist dict in dictlist: newdict['newurl'] = dict['url'] newdict['newtitle'] = dict['content'] newdict['sumvalue'] = ????? #so 1st item 'sumvalue'= + z + d = 10 + 0 + 80 = 90 (zero 'z') #and 2nd item has 'sumvalue' = + z + d = 19 + 25 + 60 = 104 print newdict[0] # should result {'newurl': 'google.com', 'newtitle': 'google', 'sumvalue' : 80 }
i don't know how iterate through dict
of dictlist
sum of values list sumlist[]
i need sum of values of respective dictionary items.
please suggest.
it looks want new list of dictionaries sums inside:
dictlist = [{'url': 'google.com', 'a': 10, 'content': 'google', 'd': 80, 'f': 1, 'lock': 'dd'}, {'url': 'fb.com', 'z': 25, 'content': 'google', 'd': 60, 'p': 1, 'a': 19}] result = [] sumlist = ['a', 'z', 'd'] d in dictlist: result.append({'newurl': d['url'], 'newtitle': d['content'], 'sumvalue': sum(d.get(item, 0) item in sumlist)}) print result
prints:
[{'newtitle': 'google', 'sumvalue': 90, 'newurl': 'google.com'}, {'newtitle': 'google', 'sumvalue': 104, 'newurl': 'fb.com'}]
or, same in one-line:
print [{'newurl': d['url'], 'newtitle': d['content'], 'sumvalue': sum(d.get(item, 0) item in ['a', 'z', 'd'])} d in dictlist]
Comments
Post a Comment