Python 3列表到字典

tpxzln5u  于 2023-03-31  发布在  Python
关注(0)|答案(4)|浏览(103)

我有三个列表,我想用它们建立一个字典:

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

我希望有:

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

我现在能做的就是:

{'a':1,'b':2, 'c':3}

我该怎么办?

5kgi1eie

5kgi1eie1#

你可以试试这个:

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

new_dict = {i:[j, k] for i, j, k in zip(a, b, c)}

输出:

{'b': [2, 5], 'c': [3, 6], 'a': [1, 4]}

如果你真的想要一个排序后的结果,你可以试试这个:

from collections import OrderedDict

d = OrderedDict()

for i, j, k in zip(a, b, c):
    d[i] = [j, k]

现在,您有了一个键按字母顺序排序的OrderedDict对象。

11dmarpk

11dmarpk2#

检查这个:how to zip two lists into new one我建议首先压缩B和c列表,然后再次使用zip将它们Map到字典中:

a = ['a','b','c']
b = [1,2,3]
c = [4,5,6]
vals = zip(b,c)
d = dict(zip(a,vals))
print(d)
lmyy7pcs

lmyy7pcs3#

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

result = { k:v  for k,*v in zip(a,b,c)}

结果

print(result)
cld4siwp

cld4siwp4#

Promotion_or_Not = "Yes","Yes","No","Yes","Yes","Yes","Yes","No","Yes","No"
Nopay_leave_or_not ="No","No","Yes","Yes","No","Yes","Yes","No","Yes","No"

Last_year_evaluation = "Good","Bad","Moderate","Good","Moderate","Moderate","Good","Bad","Good","Moderate"

mydict = {'Promotion_or_Not': [Promotion_or_Not],'Nopay_leave_or_not': [Nopay_leave_or_not], 'Last_year_evaluation':[Last_year_evaluation] }
print(mydict)

相关问题