简体   繁体   English

计算字典列表中特定字典值的出现次数并使用该计数创建一个新字典

[英]Count occurrences of specific dict value in list of dicts and create a new dict with that count

I have a list of dictionaries and what I want to do is to look for an specific value in all the dictionaries that my list have.我有一个字典列表,我想做的是在我的列表中的所有字典中查找特定值。 Then I want to create a new dictionary with that value.然后我想用那个值创建一个新字典。

Input:输入:

{ "Element": ["Box"]
  "Element2": ["Pen"]
}

{ "Element": ["Box"]
  "Element2": ["Pencil"]
}

]

Expected Output:

[
{ There are two box 
 There is one pen 
There is one pencil 
}
{ "Element": ["Box"]
  "Element2": ["Pen"]
}

{ "Element": ["Box"]
  "Element2": ["Pencil"]
}

] ```

How would you do that? Thanks in advance

To simplify the code, the values of the dictionaries are strings instead of list here, but maybe some snippet helps you.为了简化代码,字典的值在这里是字符串而不是列表,但也许一些片段可以帮助你。

from functools import reduce

dictlist=[{ "Element": "Box", "Element2": "Pen"},{ "Element": "Box","Element2": "Pencil"}]

vals=reduce(lambda x,y:x+y,[list(dic.values()) for dic in dictlist])
for val in set(vals):
    print(f"There is {vals.count(val)} {val}")

Outputs:输出:

There is 1 Pen
There is 1 Pencil
There is 2 Box

You can simply get a list of all the values using dict.values() , and the use .count(text) to count the amount of occurrences of one type of element.您可以使用dict.values()简单地获取所有值的列表,并使用.count(text)来计算一种元素的出现次数。 Counting multiple ones might be what you want though.不过,计算多个可能是您想要的。

Let's use your example.让我们用你的例子。

elements = [
{ "Element": ["Box"], "Element2": ["Pen"]},
{ "Element": ["Box"], "Element2": ["Pencil"]}]

total = []
for i in elements:
    for j in i.values():
        total.extend(j)

counts = {}
for i in total:
    if i in counts.keys():
        counts[i]+=1
    else:
        counts[i] = 1

print(counts)

EDIT: After seeing Luka's request about an element3 NOT being added to the count, here is the adjusted code, with a list of blocked elements.编辑:在看到 Luka 关于未将 element3 添加到计数中的请求后,这里是调整后的代码,带有被阻止元素的列表。

elements = [
{ "Element": ["Box"], "Element2": ["Pen"], "Element3": ["Scissor"]},
{ "Element": ["Box"], "Element2": ["Pencil"], "Element3": ["Highlighter"]}]

blocked = ["Element3"]
total = []
for i in elements:
    for key, value in i.items():
        if key not in blocked:
            total.extend(value)

counts = {}
for i in total:
    if i in counts.keys():
        counts[i]+=1
    else:
        counts[i] = 1

print(counts)

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

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