字典搜索列表

时间:2015-09-21 01:42:10

标签: python list dictionary python-3.4

我有一个字典列表如下

list1 = [{'3': ['0'], '10': ['2'], '9': ['8'], '6': ['8']},
         {'3': ['5'], '9': ['0'], '2': ['3']},
         {'2':['10'],'10':['8'],'4' :['9']}]

我还有另一个列表

list2 = [0,1,2,3,5,6,7,8,9,10]

我想检查list2的每个值是否是list1的任何字典的键,然后如果它与键匹配,那么我希望所有值与这些键相关联并添加这些值。我如何以非常优化的方式在python中实现这一点,因为我的字典列表非常大。

4 个答案:

答案 0 :(得分:3)

from collections import defaultdict
dct = defaultdict(list)
for x in list1:
    for y,z in x.items():
        dct[int(y)].append(int(z[0]))
for x in list2:
    if x in dct:
        print sum(dct[x])

答案 1 :(得分:2)

因为您的词典列表非常大,所以预处理是必要且有效的。

SumKey = {}
for item in list1:
    for key in item.keys():
        if key not in SumKey:
            SumKey[key] = 0
        SumKey[key] += item[key]

SumList = []
for item in list2:
    if item in SumKey.keys():
        SumList.append(SumKey[item])
    else:
        SumList.append(0)

答案 2 :(得分:0)

以上答案非常pythonic,可能有点迟钝。

这是一个更具可读性(但不是最高性能!):

list1=[{'3': ['0'], '10': ['2'], '9': ['8'], '6': ['8']},\
       {'3': ['5'], '9': ['0'], '2': ['3']},\
       {'2':['10'],'10':['8'],'4' :['9']}]

list2 = [0,1,2,3,5,6,7,8,9,10]
strlist2 = [str(x) for x in list2]

total = 0
for subdict in list1:
    filtered = [v for k, v in subdict.items() if k in strlist2]

    print(filtered)

    for sublist in filtered:
        print(sublist)

        for val in sublist:
            total += int(val)

print(total)

答案 3 :(得分:0)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<body>
  <div class="main"></div>
  <button>
    <img src="cat/grey-cat-001.gif">
  </button>
</body>