简体   繁体   English

从python中的字典中获取键值

[英]get keys value's from dictionary in python

I have a 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 to create a new dictionary from above dictlist . 我需要建立一个新的字典从上面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 }

I don't know how to iterate through the dict of dictlist so as to get sum of all values from list sumlist[] 我不知道如何遍历dict dictlistdict ,以便从列表sumlist[]获取所有值的总和。

I need to get sum of values of all respective dictionary items. 我需要获取所有相应字典项的值之和。

Please suggest. 请提出建议。

It looks like you want a new list of dictionaries with 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']
for d in dictlist:
    result.append({'newurl': d['url'],
                   'newtitle': d['content'],
                   'sumvalue': sum(d.get(item, 0) for item in sumlist)})

print result

prints: 打印:

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

Or, the same in one-line: 或者,单行相同:

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

Using dict.get(key, defaultvalue) , you get defaultvalue if key is not in the dictionary. 使用dict.get(key, defaultvalue) ,如果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'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM