将2D列表列表转换为字典

时间:2019-11-15 04:15:00

标签: python python-3.x list dictionary for-loop

我正在尝试将列表列表转换为字典。 每个列表必须包含2个元素,如果没有,则应附加第二个元素“ None”。那就是我()困住的地方。

表格的初始列表:

test = [['A', 27], ['B', 33], ['C', 42], ['D']]

最终字典的格式应为:

dictionary = {'A': 27, 'B':33, 'C': 42, 'D': 'None'}

我是编码的新手,for循环对我来说是一个弱点。 我开始是:

for n in range(0, len(test1)):
    d = dict(test1[n])

但是我很好,真的迷路了。

我的思维过程是:获取列表的所有元素(每个子列表)并将“无”附加到任何一维元素上……我只是不确定如何做到这一点。

2 个答案:

答案 0 :(得分:0)

想通了...我想我的问题措辞有点差。问题的症结在于遍历列表以确保所有子列表都包含2个元素。

# Declare test list
test = [['A', 27], ['B', 33], ['C', 42], ['D']]

# Create max len variable
max_len = max(len(item) for item in test)

# Verify all lists within test contain 2 elements
# If not, append 'none'
for item in test:
  while len(item) < max_len:
    item.append(None)
test

# Create dictionary from list
contacts_dict = dict(test)
contacts_dict

答案 1 :(得分:0)

您可以随时过滤:

d = {x[0]: x[1] if len(x) == 2 else None for x in test}

或者您可以使用dict构造函数:

d = dict(x if len(x) == 2 else (x[0], None) for x in test)
相关问题