首页 > 解决方案 > 如何获取二维字符串列表并返回字典?每行的第一个元素是键

问题描述

获取字符串的二维列表(即列表列表)。它返回一个字典,其键是每行的第一个元素,并且每个这样的键都映射到由该行的其余元素组成的列表。

一直在为试图解决这个问题的极客寻找极客。我知道如何到达我想从中提取的第一个列表,但我不知道如何访问每个列表,然后将其作为值放入新字典中,其余字符串作为字典中的值。


def list2dict(list2d):
    new_dict = {}
    for i in range(list2d[0]):
        for j in range(2):
            new_dict.append[j] + ':' + list2d[j]
        return new_dict


list2d is a 2d list of strings

Input:

1. Let x1 be the following list of lists:
[ [ 'aa', 'bb', 'cc', 'dd' ],
  [ 'ee', 'ff', 'gg', 'hh', 'ii', 'jj' ],
  [ 'kk', 'll', 'mm', 'nn' ] ]

Output:
Then list2dict(x1) returns the dictionary
{ 'aa' : [ 'bb', 'cc', 'dd' ],
  'ee' : [ 'ff', 'gg', 'hh', 'ii', 'jj' ],
  'kk' : [ 'll', 'mm', 'nn' ]
}

Input
2. Let x2 be the following list of lists:
[ [ 'aa', 'bb' ],
  [ 'cc', 'dd' ],
  [ 'ee', 'ff' ],
  [ 'gg', 'hh' ],
  [ 'kk', 'll' ] ]

Output
Then list2dict(x2) returns the dictionary
{ 'aa' : [ 'bb' ],
  'cc' : [ 'dd' ],
  'ee' : [ 'ff' ],
  'gg' : [ 'hh' ],
  'kk' : [ 'll' ]
}

标签: python-3.x

解决方案


我想你正在寻找这样的东西...... 在线版

def list2dict(list2d):
    new_dict = {}
    for i in list2d:
        key = i[0]
        list = i[1:len(i)]
        new_dict[key] = list
    print(new_dict)
    return new_dict

推荐阅读