Is there a function to filter my dictionary with another dictionary?

Viewed 41

I am trying to filter my dictionary LOCATION with the dictionary LOCATION_SUPPLY_OPEN. If the value of LOCATION_SUPPLY_OPEN equals 1, the new_dict should have the key (which equals 1) in it with the value of the dictionary LOCATION with the same key.

I tried it with different functions but it didn't work hope you can help me because I am quite new to python Thanks!


LOCATION = {
    'Berlin': (13.404954, 52.520008), 
    'Cologne': (6.953101, 50.935173),
    'Hamburg': (9.993682, 53.551086),
    'Stuttgart': (9.181332, 48.777128),
    'Munich': (11.576124, 48.137154),
    }


# Open Location Dictionary kinda Binary,  1:open Location, 0:otherwise
LOCATION_SUPPLY_OPEN = {
    'Berlin': (0), 
    'Cologne': (1),
    'Hamburg': (0),
    'Stuttgart': (1),
    'Munich': (1),
    }

new_dict = {}
# new_dict should have the keys from LOCATION_SUPPLY_OPEN with a value of 1 and the values of LOCATION
#  new_dict = {"Cologne":(6.953101, 50.935173), 'Stuttgart': (9.181332, 48.777128),'Munich': (11.576124, 48.137154) }


#Here I have tried it but it didn't work

LOCATIONS = {}

for (key,value) in LOCATION_SUPPLY_OPEN.items():
    if value > 0:
        LOCATIONS[key] = LOCATION[value]

1 Answers

You did almost everything, except assigning proper values to the new_dict

Check out this one:

LOCATION_SUPPLY_OPEN = {
    'Berlin': (0), 
    'Cologne': (1),
    'Hamburg': (0),
    'Stuttgart': (1),
    'Munich': (1),
    }
    
LOCATION = {
    'Berlin': (13.404954, 52.520008), 
    'Cologne': (6.953101, 50.935173),
    'Hamburg': (9.993682, 53.551086),
    'Stuttgart': (9.181332, 48.777128),
    'Munich': (11.576124, 48.137154),
    }
    
new_dict = {}

#  new_dict = {"Cologne":(6.953101, 50.935173), 'Stuttgart': (9.181332, 48.777128),'Munich': (11.576124, 48.137154) }

for key, value in LOCATION_SUPPLY_OPEN.items():
    if value:
       new_dict[key] = LOCATION[key]
       
print(new_dict)

With Dict Comprehension:

new_dict = {key: LOCATION[key] for (key, value) in LOCATION_SUPPLY_OPEN.items() if value}

More optimizations are welcome ;)

Related