简体   繁体   English

python 中的字典理解问题

[英]Dictionary comprehension problem in python

A=[1,2,3,4,5]
B=['a','b','c']

I want output:我想要 output:

{1: 'a', 2: 'b', 3: 'c', 4: None, 5: None}

We can have any number of keys.我们可以有任意数量的键。

I want to create a dictionary with these two lists using dictionary comprehension in python and list A will become keys and other is value for key 4 and 5 we have to print None and other keys with corresponding values how can we do it using dict comprehension.我想在 python 中使用字典理解创建一个包含这两个列表的字典,列表 A 将成为键,其他是键 4 和 5 的值,我们必须打印 None 和其他具有相应值的键我们如何使用字典理解来做到这一点。 Thanks in advance.提前致谢。

[None]*(len(a)-len(b)) will create n (Here, it is len(a)-len(b) )) time None and you can use += to add them in to list: [None]*(len(a)-len(b))将创建 n (这里是len(a)-len(b) )) 时间 None 并且您可以使用+=将它们添加到列表中:

b += [None]*(len(a)-len(b))

And you can make a dictionary by using dict() function:您可以使用dict() function 制作字典:

dict(zip(a,b))

Full code:完整代码:

a = [1, 2, 3, 4, 5]
b = ['a', 'b', 'c']

b += [None]*(len(a)-len(b))

dic = dict(zip(a, b))
print(dic)



Note : 注意
If you don't know which is the longest list then you can use: 如果您不知道哪个是最长的列表,那么您可以使用:

 if len(a) > len(b): b += [None]*(len(a)-len(b)) elif len(a) < len(b): a += [None]*(len(b)-len(a))

In len(a) < len(b) case None will be overwrite and value of None and it will be last item in b.len(a) < len(b)情况下None 将被覆盖并且值为 None 并且它将是 b 中的最后一项。 To avoid that you can use dict(zip(b, a)) instead of dict(zip(a, b)) .避免这种情况,您可以使用dict(zip(b, a))代替dict(zip(a, b)) Then you should change the full code as follow, but it changes your output (Ex: {'a': 1, 'b': 2, 'c': None} ):然后你应该改变完整的代码如下,但它会改变你的 output (例如: {'a': 1, 'b': 2, 'c': None} ):

 a = [1, 2] b = ['a', 'b', 'c'] if len(a) > len(b): b += [None]*(len(a)-len(b)) dic = dict(zip(a, b)) elif len(a) < len(b): a += [None]*(len(b)-len(a)) dic = dict(zip(b, a)) else: dic = dict(zip(a, b)) print(dic)
def dict_maker(keys, values):
    dict = {}
    for i, key in enumerate(keys):
        try:
            dict[key] = values[i]
        except IndexError:
            dict[key] = None
    return dict

The way to go is to use itertools.zip_longest , as already suggested in the comments.正如评论中已经建议的那样,通往 go 的方法是使用itertools.zip_longest zip_longest uses None as default for the missing values in the shortest list, which is exactly what you want: zip_longest使用None作为最短列表中缺失值的默认值,这正是您想要的:

from itertools import zip_longest

out = dict(zip_longest(A, B))

. . You can also achieve this without importing anything, by using zip , which will only consume the common start of the two list, then update this dict with another one which has the remaining values from the second list as keys, and None as values.您也可以在不导入任何内容的情况下实现此目的,方法是使用zip ,它只会消耗两个列表的共同开始,然后用另一个将第二个列表中的剩余值作为键的字典更新这个字典,并将 None 作为值。 dict_fromkeys builds exactly that by default:默认情况下, dict_fromkeys完全是这样构建的:

A = [1, 2, 3, 4, 5]
B = ['a', 'b', 'c']

out = dict(zip(A, B))
out.update(dict.fromkeys(A[len(B):]))

print(out)
# {1: 'a', 2: 'b', 3: 'c', 4: None, 5: None}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM