有没有用另一个字典过滤我的字典的功能?

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

我正在尝试使用字典 LOCATION_SUPPLY_OPEN 过滤我的字典 LOCATION。 如果 LOCATION_SUPPLY_OPEN 的值等于 1,则 new_dict 中应该有键(等于 1)和具有相同键的字典 LOCATION 的值。

我尝试了不同的功能,但没有用 希望你能帮助我,因为我对 python 很陌生 谢谢!


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]

除了为 new_dict

分配适当的值外,您几乎完成了所有操作

看看这个 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)

用字典理解:

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

欢迎更多优化;)