2013-08-24 3 views
1

У меня есть список словаря:получить ключи-значения из словаря в Python

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}] 

Мне нужно создать новый словарь из выше dictlist.

newdict= {} 
    sumlist = ['a', 'z', 'd'] #Get values for these from dictlist 
    for dict in dictlist: 
     newdict['newurl'] = dict['url'] 
     newdict['newtitle'] = dict['content'] 
     newdict['sumvalue'] = ????? 
       #so that for 1st item its 'sumvalue'= a + z + d = 10 + 0 + 80 = 90 (zero for 'z') 
       #and 2nd item has 'sumvalue' = a + z + d = 19 + 25 + 60 = 104 

print newdict[0] # should result {'newurl': 'google.com', 'newtitle': 'google', 'sumvalue' : 80 } 

Я не знаю, как перебирать dict из dictlist так, чтобы получить сумму всех значений из списка sumlist[]

Мне нужно, чтобы получить сумму значений всех соответствующих словарных элементов.

Просьба предложить.

ответ

1

Похоже, что вы хотите новый список словарей с суммами внутри:

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'] 
for d in dictlist: 
    result.append({'newurl': d['url'], 
        'newtitle': d['content'], 
        'sumvalue': sum(d.get(item, 0) for item in sumlist)}) 

print result 

печатает:

[{'newtitle': 'google', 'sumvalue': 90, 'newurl': 'google.com'}, 
{'newtitle': 'google', 'sumvalue': 104, 'newurl': 'fb.com'}] 

Или же в одно- line:

print [{'newurl': d['url'], 'newtitle': d['content'], 'sumvalue': sum(d.get(item, 0) for item in ['a', 'z', 'd'])} for d in dictlist] 
0

Используя dict.get(key, defaultvalue), вы получаете значение по умолчанию, если ключ не находится в словаре.

>>> d = {'a': 1, 'b': 2} 
>>> d.get('a', 0) 
1 
>>> d.get('z', 0) 
0 

>>> 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} 
... ] 
>>> 
>>> newdictlist = [] 
>>> sumlist = ['a', 'z', 'd'] 
>>> for d in dictlist: 
...  newdict = {} 
...  newdict['newurl'] = d['url'] 
...  newdict['newtitle'] = d['content'] 
...  newdict['sumvalue'] = sum(d.get(key, 0) for key in sumlist) 
...  newdictlist.append(newdict) 
... 
>>> newdictlist[0] 
{'newtitle': 'google', 'sumvalue': 90, 'newurl': 'google.com'} 
>>> newdictlist[1] 
{'newtitle': 'google', 'sumvalue': 104, 'newurl': 'fb.com'} 
Смежные вопросы