迭代子列表以创建字典

时间:2017-03-08 07:49:50

标签: python dictionary

我想迭代列表中的子列表以创建一个字典,其中子列表的元素是键,广告值都是0。

示例:

keys = [['desk','lamp','printer'],['mouse','chair','desk','pencil']]

我想要输出:

output = [{'desk':0,'lamp':0,'printer':0},{'mouse':0,'chair':0,'desk':0,'pencil':0}]

我尝试了以下但是没有工作:

d = {}
output= []

for i in range(len(keys)):
    for w in keys[i]:
        output.append(d[w] = 0)

但是当我运行这个时,我收到一条消息,关键字不能成为表达式。

由于我在键的子列表中有不同的元素,我该怎么做?

5 个答案:

答案 0 :(得分:6)

您可以将列表理解和dict.fromkeys0一起用作值:

>>> keys = [['desk','lamp','printer'],['mouse','chair','desk','pencil']]
>>> [dict.fromkeys(l, 0) for l in keys]
[{'desk': 0, 'lamp': 0, 'printer': 0}, {'mouse': 0, 'desk': 0, 'pencil': 0, 'chair': 0}]

赋予fromkeys的第一个参数是可迭代的键,第二个参数是为每个键设置的值。

答案 1 :(得分:3)

另一种简单方法:

[{y:0 for y in x} for x in keys]

答案 2 :(得分:2)

您可以在列表理解中嵌套词典理解:

>>> keys = [['desk','lamp','printer'],['mouse','chair','desk','pencil']]
>>> [{k:0 for k in ks} for ks in keys]
[{'printer': 0, 'desk': 0, 'lamp': 0}, {'desk': 0, 'pencil': 0, 'mouse': 0, 'chair': 0}]
>>>

答案 3 :(得分:1)

试试这个:

keys = [['desk','lamp','printer'],['mouse','chair','desk','pencil']]
output= []

for i in range(len(keys)):
    d = {}
    for w in keys[i]:
        d[w] = 0
    output.append(d)

答案 4 :(得分:1)

abc = [['desk','lamp','printer'],['mouse','chair','desk','pencil']]

new_array = []
for array in abc:
    dic = {}
    for value in array:
        dic[value] = 0
    new_array.append(dic)

print(new_array)

keys在python中很特别,避免使用它:D