-1

I have a list as below:

fruits_exclude = ['grapes', 'banana', 'apple']

I have two dictionaries as below:

fruits_have = {'apple': 3, 'banana': 4, 'mango': 5, 'grapes': 5}

final_dict = {}

I want to move the item 'mango': 5 into final_dict.

I am trying to do it in python, but things are not working:

if list(fruits_have.keys()) not in fruits_exclude:
    #copy the key and value pair (item) into final_dict 

Could someone help me with this?

NewToCoding
  • 199
  • 1
  • 2
  • 15
  • `fruits_exclude` does not contain lists, so converting the keys to a list and checking if it's there will surely not work. You want to iterate and check ***each key*** to check if it's in the list. If not, add it with its value to the final dict – Tomerikoo Aug 01 '22 at 14:01

2 Answers2

1
final_dict = {key: val for (key,val) in fruits_have.items() if key not in fruits_exclude}
ArrowRise
  • 608
  • 2
  • 7
  • 2
    A single line without any explanations will hardly help for someone that was barely able to get to a solution for this issue... – Tomerikoo Aug 01 '22 at 14:02
1

You could iterate over the keys of your dictionary, and add every key that is not in the fruits_exclude to final dict

fruits_exclude = ['grapes', 'banana', 'apple']
fruits_have = {'apple': 3, 'banana': 4, 'mango': 5, 'grapes': 5}
final_dict = {}
fruit_set = set(fruits_exclude)
for fruit in fruits_have.keys():
    if fruit not in fruit_set:
        final_dict[fruit] = fruits_have[fruit]
print (final_dict)

output:

{'mango': 5}

hope this was clear enough

and feel free to ask me for any clarifications in the comments :)

Ohad Sharet
  • 1,097
  • 9
  • 15