繁体   English   中英

Python字典从两个字典中提取数据并插入新字典

[英]Python dictionary extract data from two dictionaries and insert in new dictionary

我是一名 Python 初学者,正在努力使用字典。

我有字典 routesAndID 和 findOutPlane:

routesAndID = {('Sydney', 'Dubai'): 3, ('New York', 'Los Angeles'): 2, ('Zurich', 'Singapore'): 0}

findOutPlane = {('Sydney', 'Dubai'): 'Airplane', ('New York', 'Los Angeles'): 'Helicopter', ('Zurich', 'Singapore'): 'Jet'}

我需要在路线匹配时提取飞机和相应的ID(根据路线,可以识别飞机)。 我需要以下输出:

newdict = { "Airplane": 3, "Helicopter": 2, "Jet": 0 }

有人知道该怎么做吗?

您可以根据 findOutPlane 的值创建newdict ,该值与findOutPlane中的值与routesAndID中的键findOutPlane

newdict = { value : routesAndID.get(key, -1) for key, value in findOutPlane.items() }

输出:

{'Airplane': 3, 'Helicopter': 2, 'Jet': 0}

请注意,如果findOutPlane中的键不存在,我已经为从routesAndID获取(使用routesAndID.get(key, -1) )设置了默认值-1 如果不是这种情况,您可以简单地使用routesAndID[key] ,即

newdict = { value : routesAndID[key] for key, value in findOutPlane.items() }

考虑使用dict comprehension

>>> route_to_id = {
...     ('Sydney', 'Dubai'): 3,
...     ('New York', 'Los Angeles'): 2,
...     ('Zurich', 'Singapore'): 0
... }
>>> route_to_aircraft = {
...     ('Sydney', 'Dubai'): 'Airplane',
...     ('New York', 'Los Angeles'): 'Helicopter',
...     ('Zurich', 'Singapore'): 'Jet'
... }
>>> aircraft_to_id = {
...   aircraft: route_to_id[route]
...   for route, aircraft in route_to_aircraft.items()
... }
>>> aircraft_to_id
{'Airplane': 3, 'Helicopter': 2, 'Jet': 0}

如果可能有多条具有相同飞机类型的路线,您可以使用collections. defaultdict collections. defaultdict

>>> from collections import defaultdict
>>> route_to_id = {
...     ('Sydney', 'Dubai'): 3,
...     ('New York', 'Los Angeles'): 2,
...     ('Zurich', 'Singapore'): 0,
...     ('Auckland', 'San Francisco'): 4
... }
>>> route_to_aircraft = {
...     ('Sydney', 'Dubai'): 'Airplane',
...     ('New York', 'Los Angeles'): 'Helicopter',
...     ('Zurich', 'Singapore'): 'Jet',
...     ('Auckland', 'San Francisco'): 'Airplane'
... }
>>> aircraft_to_ids = defaultdict(list)
>>> for route, aircraft in route_to_aircraft.items():
...     aircraft_to_ids[aircraft].append(route_to_id[route])
... 
>>> dict(aircraft_to_ids)
{'Airplane': [3, 4], 'Helicopter': [2], 'Jet': [0]}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM