如何将单个列表的元素转换为字典形式

6
我希望您将以下列表转换为字典。
sample_list=['A', 'B', 'C', 'D']

预期的字典如下所示

out_dict = {'A':'B','C':'D'}
6个回答

5

你可以使用:

dict(zip(sample_list[::2], sample_list[1::2]))

zip 函数用于创建新字典的键值对。


使用迭代器的变体(因此避免复制列表)是使用zip(it, it)在列表上成对迭代,然后从中创建字典:
it = iter(sample_list)
dct = dict(zip(it, it))

Python>=3.8中,您将能够使用赋值表达式,并以一个漂亮的一行代码完成所需操作。

dct = dict(zip(it := iter(sample_list), it))

1
"在巴黎迭代"很不错。 ;) - Matthias
嗯,现在我不能再修正拼写错误了。所以我会假装我是有意这样写的!你应该去巴黎遍历迭代!春天的巴黎很美丽。 - hiro protagonist

3
您可以使用以下字典推导式:
{x:y for x,y in zip(sample_list[::2], sample_list[1::2])}
# {'A': 'B', 'C': 'D'}

3

假设列表元素个数为偶数,请尝试以下方法:

{ sample_list[i] : sample_list[i+1] for i in range(0, len(sample_list) - 1, 2) }

这个解决方案的优点是在Python 3.x下不会创建中间列表,在Python 2.x中只需用xrange替换range即可。


3

这个示例可以处理不均匀的列表(在正常情况下会导致Python崩溃)

sample_list= ['A', 'B', 'C', 'D','E','F','G','H']
output = {}
for i in range(0,len(sample_list),2):
    #print(sample_list[i],sample_list[i+1])
    if (i+1) < len(sample_list): #Dont need this line, just avoids python
    #crashing if the list isn't even.
        temp = {sample_list[i]:sample_list[i+1]}
        output.update(temp)
    else:
        print("ERROR: LIST NOT EVEN, WILL NOT INCL. Last Item.")
print(output)

生成以下输出:
{'A': 'B', 'C': 'D', 'E': 'F', 'G': 'H'}

3

您可以使用一个带有迭代器的字典推导:

lst = ['A', 'B', 'C', 'D']

it = iter(lst)
{k: next(it) for k in it}
# {'A': 'B', 'C': 'D'}

你抄袭了我的原创想法!太好了。 - prosti
@prosti {k: v for k, v in zip(it, it)} 怎么样? - Mykola Zotko
@prosti 首先,您需要初始化您的迭代器 it = iter(lst) - Mykola Zotko
1
是的,你需要初始化迭代器。正如我所提到的,在Python>=3.8中,我们将能够这样做:dct = dict(zip(it := iter(sample_list), it))。多么美妙啊! - hiro protagonist

2
lst = ['A', 'B', 'C', 'D']
n = { lst[n]:lst[n+1] for n in range(0, len(lst), 2)}
n

这不就是Óscar López的答案吗? - hiro protagonist
这是我的答案。我没有作弊 ;) - prosti
我并不是在说你抄袭了(显然你没有);只是你的答案和他的差不多,而他的回答比你早了约15分钟。 - hiro protagonist
我来晚了。:] - prosti

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接