我正在尝试将列表列表转换为字典。 每个列表必须包含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])
但是我很好,真的迷路了。
我的思维过程是:获取列表的所有元素(每个子列表)并将“无”附加到任何一维元素上……我只是不确定如何做到这一点。
答案 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)