0

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)
  • 1
    This will probably be easiest with a dict comprehension: `New_Dict = {key: value for key, value in Dict1.items() if value.Average >= 0.90}` – 0x5453 Jan 17 '23 at 20:46
  • @0x5453 Why don't you use append? Anyway, out of curiosity, what was I doing wrong in my code? Thank you –  Jan 17 '23 at 20:49
  • The wrong bit in your code is exactly that you're using append :D – gimix Jan 17 '23 at 20:51
  • @gimix Why? Can you explain me? Thank you –  Jan 17 '23 at 20:53
  • `.append` is a method on `list`s. I presume that `New_Dict` does not contain `list`s, and instead you should just be using `New_Dict[key] = value`. – 0x5453 Jan 17 '23 at 20:55
  • @0x5453 OK! I got it. One question: I see that there are curly braces {...}. Does it mean I can NOT CREATE New_Dict = {} if I use your code? Or should I still create New_Dict = {} even if I use your code? Thank you –  Jan 17 '23 at 22:41

1 Answers1

1

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)
braulio
  • 543
  • 2
  • 13
  • Thank you. The print is a bit confusing. I would like to add one of the lines of space. How can I apply this code when I print the dictionary? f"{key}:\n{value}", end='\n\n' –  Jan 17 '23 at 21:18
  • try something like: https://stackoverflow.com/questions/3229419/how-to-pretty-print-nested-dictionaries – braulio Jan 17 '23 at 21:28
  • I read, but I did not understand. I thought it was easier –  Jan 17 '23 at 21:33
  • I upvoted (before) and accepted your answer now. Thank you –  Jan 17 '23 at 23:01