[英]Python filter dictionary unique values in a key and create another filtered dictionary
[英]Add dictionary key and values, if filtered with a condition, into another empty dictionary
我有字典Dict1
,我在其中過濾並僅打印算術平均值 >=90 的元素。
我想將鍵和值(以前過濾的項目)添加到一個名為New_Dict
的新空字典中。 因此New_Dict
將具有與Dict1
相同的鍵和相同的值,但它們被過濾了。
我收到此錯誤:
New_Dict[key].append(filtered)
KeyError: 'Tokyo-Osaka'
如何將Dict1
詞典中的篩選項添加到新的New_Dict
詞典中?
我的代碼是這樣的:
Dict1 = {}
New_Dict = {}
for key, value in Dict1.items():
#Filter
if value.Average >= 0.90:
filtered = key, value
#Insert in new dictionary
if key not in New_Dict:
New_Dict[key].append(filtered)
print(New_Dict)
這里:
Dict1 = {'Tokyo-Osaka':90, 'x-y': 20, 'a-b':100}
New_Dict = {}
for key, value in Dict1.items():
#Filter
if value >= 0.90:
New_Dict[key] = value
print(New_Dict)
如果您的字典中的項目有多個值,並且像您提到的那樣,您需要根據均值進行過濾:
from statistics import mean
Dict1 = {'Tokyo-Osaka':[90,90,90], 'x-y': [.20,.20,.20], 'a-b':[100,100,1000]}
New_Dict = {}
for key, value in Dict1.items():
#Filter
if mean(value) >= 0.90:
New_Dict[key] = value
print(New_Dict)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.