本文介绍了将python列表转换为字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将我的列表转换为python中的字典。我有列表l l = ['a','b','c','d']
,我想将其转换为字典d
d ['a'] = []
d ['b'] = []
d ['c'] = []
d ['d'] = []
我正在尝试
for i in range(0,len(l)):
pre>
d [i] [0] = l(i)
但这不行。谢谢
解决方案保持它比这更简单,你想循环你的列表,然后分配你的迭代器
i
(这将是您的列表中的每个值)作为每个字典条目的键。l = ['a','b','c','d']
d = {}
对于我在l:
d [i] = []
打印(d)#{'a':[],'c ':[],'b':[],'d':[]}
以上理解,您现在可以将其简化为一行:
{k:[] for k in l}
以上称为字典理解。您可以阅读
I'm trying convert my list to dictionary in python. I have list l
l = ['a', 'b', 'c', 'd']
and I want convert it to dictionary d
d['a'] = [] d['b'] = [] d['c'] = [] d['d'] = []
I was trying
for i in range(0, len(l)): d[i][0]=l(i)
but that don't work. Thanks
解决方案Keep it a bit simpler than that, you want to loop over your list, and then assign your iterator
i
(which will be each value in your list) as the key to each dictionary entry.l = ['a', 'b', 'c', 'd'] d = {} for i in l: d[i] = [] print(d) # {'a': [], 'c': [], 'b': [], 'd': []}
With the above understood, you can now actually simplify this in to one line as:
{k: [] for k in l}
The above is called a dictionary comprehension. You can read about it here
这篇关于将python列表转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!