简体   繁体   English

将列表列表转换为字典

[英]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.列表可能很长,因此需要尽可能提高效率。

The first element of each "pair" [[first, second], ...] is unique, so we can make a dictionary from it.每个“pair” [[first, second], ...]的第一个元素是唯一的,因此我们可以从中制作字典。

I tried with the following, but I think it will be slow:我尝试了以下方法,但我认为它会很慢:

def getdict(l):
    result = {}
    for e in l:
        result[int(e[0])] = e[1]
    return result

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:请注意,您会像@Kevin 的示例一样“丢失”重复项:

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

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

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