FacundoGFlores FacundoGFlores - 2 months ago 12
Python Question

Converting list of list to dictionary

I have the following list of list:

[[u'3', u'4'], [u'4', u'5'], [u'7', u'8'], [u'1', u'2'], [u'2', u'3'], [u'6', u'7'], [u'5', u'6']]


I want to obtain:

{3:'4', 4:'5', 7:'8', 1:'2', 2:'3', 6:'7', 5:'6'}


List could be long, so it needs to be more efficient as possible.

Answer

You can use a dictionary comprehension:

>>> l = [[u'3', u'4'], [u'4', u'5'], [u'7', u'8'], [u'1', u'2'], [u'2', u'3'], [u'6', u'7'], [u'5', u'6']]
>>> {int(key): value for key, value in l}
{1: u'2', 2: u'3', 3: u'4', 4: u'5', 5: u'6', 6: u'7', 7: u'8'}

Note that you would "lose" duplicates like in the @Kevin's example:

>>> l = [['1', '2'], ['1', '3']]
>>> {int(key): value for key, value in l}
{1: '3'}
Comments