Home > database >  Python dictionary extract data from two dictionaries and insert in new dictionary
Python dictionary extract data from two dictionaries and insert in new dictionary

Time:05-22

I am a Python beginner and am struggling with working with dictionaries.

I have the dictionaries routesAndID and 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'}

I need to extract the Aircraft and the corresponding ID on match of routes (depending on routes, the aircraft can be identified). I need the following output:

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

Would anyone know how to do so?

CodePudding user response:

Consider using a 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}

If there could be multiple routes with the same aircraft type you could utilize 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]}

CodePudding user response:

You can create newdict from the values of findOutPlane matched with the value from routesAndID corresponding to the key from findOutPlane:

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

Output:

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

Note I've set a default value of -1 for the fetch from routesAndID (using routesAndID.get(key, -1)) in case the key from findOutPlane is not present. If that will not be the case, you can simply use routesAndID[key] instead i.e.

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