簡體   English   中英

計算字典列表中特定字典值的出現次數並使用該計數創建一個新字典

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

我有一個字典列表,我想做的是在我的列表中的所有字典中查找特定值。 然后我想用那個值創建一個新字典。

輸入:

{ "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

為了簡化代碼,字典的值在這里是字符串而不是列表,但也許一些片段可以幫助你。

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}")

輸出:

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

您可以使用dict.values()簡單地獲取所有值的列表,並使用.count(text)來計算一種元素的出現次數。 不過,計算多個可能是您想要的。

讓我們用你的例子。

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)

編輯:在看到 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