python - dictionary comprehension derived from existing lists -


as part of bigger exercise, trying construct dictionary based on inputs smaller lists, struggling embedded iteration. suppose have following illustrative example:

cities = ['newyork','london','tokyo','paris'] citypairs = [i in it.combinations(cities,2)] airlines = ['delta', 'united'] 

i want construct dictionary of dictionaries, "info", keys combinations of cities above + each airline (so 12 total keys), , each of keys contains "city1" , "city2" key populated using citypairs list. trying like:

info = { '{city1}/{city2} {airline}'.format(city1=city1, city2=city2, airline=airline): {     "city1": city1, "city2": city2     city1, city2 in citypairs     }     city1, city2 in citypairs     airline in airlines     }  

but receiving invalid syntax error. more illustrate after, if instead of above attempt, do:

info = { '{city1}/{city2} {airline}'.format(city1=city1, city2=city2, airline=airline): {     "city1": "whatever", "city2": "whatever"     }     city1, city2 in citypairs     airline in airlines     }  

then run , create dummy values of 'whatever' city1 , city2 each key in "info"

this example might seem silly or overly complicated, heart of question how can iterate through list of tuples populate city1 , city2 in example - after because real-life project working on need sort of flexibility

my belief solution simpler you're making it:

from itertools import combinations  cities = ['newyork','london','tokyo','paris'] citypairs = combinations(cities, 2) airlines = ['delta', 'united']  info = {'{city1}/{city2} {airline}'.format(city1=city1, city2=city2, airline=airline): {"city1": city1, "city2": city2}     city1, city2 in citypairs         airline in airlines  }   print(info) print() print(info["newyork/london delta"]["city1"]) 

output

{'london/tokyo delta': {'city1': 'london', 'city2': 'tokyo'}, 'newyork/london delta': {'city1': 'newyork', 'city2': 'london'}, 'london/paris delta': {'city1': 'london', 'city2': 'paris'}, 'london/tokyo united': {'city1': 'london', 'city2': 'tokyo'}, 'tokyo/paris united': {'city1': 'tokyo', 'city2': 'paris'}, 'newyork/paris delta': {'city1': 'newyork', 'city2': 'paris'}, 'tokyo/paris delta': {'city1': 'tokyo', 'city2': 'paris'}, 'newyork/paris united': {'city1': 'newyork', 'city2': 'paris'}, 'london/paris united': {'city1': 'london', 'city2': 'paris'}, 'newyork/london united': {'city1': 'newyork', 'city2': 'london'}, 'newyork/tokyo delta': {'city1': 'newyork', 'city2': 'tokyo'}, 'newyork/tokyo united': {'city1': 'newyork', 'city2': 'tokyo'}}

newyork


Comments