Home > Net >  I have a nested list and would like to extract parts of it using list comprehension
I have a nested list and would like to extract parts of it using list comprehension

Time:05-19

I have a nested list named list1 of following:

 list1 = [['Plane' , 'London' , 'Paris', '1']  ,  ['Helicopter', 'Budapest' , 'Rome', '2']  ,  ['Jet', 'Tokio', 'New York' , '3'] ,  ['Balloons' , 'Belgrade', 'Vienna', '2']]

I need to extract the following from list1 in python:

 { ('London', 'Paris'): '1', 
 ('Budapest', 'Rome'): '2',
('Tokyo', 'New York'): '3',
('Belgrade', 'Vienna'): '2'}

How can I solve this with list comprehension?

CodePudding user response:

This works

# unpack each sub-list in a dict comprehension and manually construct the keys
{(i,j): v for _,i,j,v in list1}
{('London', 'Paris'): '1',
 ('Budapest', 'Rome'): '2',
 ('Tokio', 'New York'): '3',
 ('Belgrade', 'Vienna'): '2'}
  • Related