Add dictionary key and values, if filtered with a condition, into another empty dictionary

Question:

I have the dictionary Dict1 in which i filter and print only the elements that have an arithmetic mean >=90.

I would like to add the key and values (of previously filtered items) into a new empty dictionary called New_Dict. So New_Dict will have the same key and the same values as Dict1, but they are filtered.

I get this error:

     New_Dict[key].append(filtered)
KeyError: 'Tokyo-Osaka'

How can I add the filtered items from the Dict1 dictionary into the new New_Dict dictionary?

My code is this:

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)
Asked By: Takao貴男

||

Answers:

here:

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)

if the items of your dictionary have multiple values, and like you mentioned you need to filter on the basis of the mean:

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)
Answered By: braulio