python - 从Python中的字典中获取键值

标签 python list for-loop dictionary iterator

我有一个字典列表:

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 }

我不知道如何迭代 dictlistdict 以获得列表 sumlist[] 中所有值的总和

我需要获取所有相应字典项的值的总和。

请提出建议。

最佳答案

看起来您想要一个新的字典列表,其中包含总和:

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

或者,在一行中相同:

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

关于python - 从Python中的字典中获取键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18416134/

相关文章:

for-loop - 字符串 slice 的范围不一致

c++ - 为什么for循环没有停止?

excel - 显示错误消息并恢复循环

python - C数组与NumPy数组

python - 相同条件日期 True with Series 但 False using element

python - 以 SMT2 格式保存 Z3 解算器的 "state"

c# - List<Object> 的 XML 序列化

python - 如何访问字典 python 中列表中的元素?

python - 如何从不同的索引开始迭代列表,并环绕

python - 如何在 Python 中创建 N 元组?