如何遍历字典字典并提取与python中的列表元素匹配的值?

时间:2014-11-15 00:25:38

标签: python

我有两个这样的列表:

l = [ 'of', 'in', 'fly']

l2 = ['starbucks', 'the', 'and', '.', ',', 'from', 'to']

和这样的字典:

d = { of : {in : 1, and : 2, to: 0}, in : { of : 2,  and : 5, to : 3}, and : {of : 3, in: 6, to: 2}, to: {and: 1, of: 0, in: 3}}

我想从列表l遍历,如果字典d中列表l中有单词的键,则遍历列表l2并匹配内部字典中的键(即值对于来自外部字典的匹配键,并且仅从内部字典中提取这些键值,作为来自外部字典的该键的值。 如果单词不在d中,则将其添加到new_dict,给它一个值0。

与上面一样,我想要一个像这样的输出:

new_dict = {of : [2, 0] , in : [5, 3], fly: 0}

因为'和'和'到'是唯一与内部词典匹配的单词。

我做的是这样的事情:

for k in l:
    if k in d:
        new_d[k]=d[k]
        d_values = new_d.values()
        for k2 in l2:
            if k2 in d_values:
                t[k2] = d_values[k2]
                temp[k] = t
    else temp[k] = 0

但我得到了temp = {}。为什么会这样?我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

from collections import defaultdict
new__d = defaultdict(list)
for k in l:
    if k in d: 
        for k2, vals in d[k].iteritems(): # list element is in d so get that keys items
            if k2 in l2:
                new__d[k].append(vals) 
    else:
        new__d[k] = 0  # presuming you want a default value of 0 for list elements that are not in d
print(new__d)

defaultdict(<type 'list'>, {'fly': 0, 'of': [2, 0], 'in': [5, 3]})

我使用了defaultdict,因为有重复键,所以我们需要附加值,否则它们会被覆盖。

如果您坚持不使用defaultdict,则可以使用dict.setdefault,但效率较低:

new__d = {}
for k in l:
    if k in d:
        for k2, vals in d[k].iteritems():
            if k2 in l2:
                new__d.setdefault(k,[])
                new__d[k].append(vals)
    else:
        new__d[k] = 0
print(new__d)