如何将四个列表添加到一个字典中

时间:2018-04-13 19:10:56

标签: python python-2.7 list dictionary for-loop

在Python中,我有4个列表,并希望其中一个成为我的字典键,其余成为我的键值,但列表长度不同

Employee_ManagerDic = {}
EmployeeID_List = [111,222,333,444,555]
EmployeeFirstName_List = ['a','b','c','d','e']
managerID_List = [888,777,666]
managerFirstName_List = ['f','g','h']

我想要的输出采用以下格式:

Employee_ManagerDic = {EmployeeID_List:[EmployeeFirstName_List,managerID_List,
managerFirstName_List]}

和类似的东西

Employee_managerDic = {
                       111:['a',888,'f'],
                       222:['b',777,'g'],
                       333:['c',666,'h'],
                       444:['d',null,null],
                       555:['e',null,null]}

我知道我可能需要使用for循环,但我不知道如何构建循环逻辑。

谢谢

5 个答案:

答案 0 :(得分:2)

由于你正在使用python2,你可以使用itertools.iziplongestdict构造函数:

from itertools import izip_longest
Employee_managerDic = dict(
    zip(
        EmployeeID_List,
        map(
            list,
            izip_longest(EmployeeFirstName_List, managerID_List, managerFirstName_List)
        )
    )
)
#{111: ['a', 888, 'f'],
# 222: ['b', 777, 'g'],
# 333: ['c', 666, 'h'],
# 444: ['d', None, None],
# 555: ['e', None, None]}

来自docs for iziplongest

  

创建一个聚合来自每个迭代的元素的迭代器。   如果迭代的长度不均匀,则填充缺失值   用fillvalue。

list(izip_longest(EmployeeFirstName_List, managerID_List, managerFirstName_List))的中间输出是:

[('a', 888, 'f'),
 ('b', 777, 'g'),
 ('c', 666, 'h'),
 ('d', None, None),
 ('e', None, None)]

然后我调用map(list, ...)来将元组转换为列表,虽然这可能不需要(我只是为了匹配你想要的输出)。

最后,我们将zipEmployeeID_List以及此输出传递给dict构造函数。

答案 1 :(得分:2)

?`%m+%`

以上是字典理解等同于:

from itertools import izip_longest

Employee_ManagerDic = {
    row[0]: row[1:]
    for row in izip_longest(EmployeeID_List,
                            EmployeeFirstName_List,
                            managerID_List,
                            managerFirstName_List)
}

Employee_ManagerDic = {} for row in izip_longest(EmployeeID_List, EmployeeFirstName_List, managerID_List, managerFirstName_List): Employee_ManagerDic[row[0]] = row[1:] 是一个片段,如果您不熟悉它并想要谷歌它。

答案 2 :(得分:1)

对于Python2.7,您可以使用带有None的地图而不是zip,这将为您提供最长的拉链。

>>>map(None, EmployeeID_List, EmployeeFirstName_List, managerID_List, managerFirstName_List) [(111, 'a', 888, 'f'), (222, 'b', 777, 'g'), (333, 'c', 666, 'h'), (444, 'd', None, None), (555, 'e', None, None)]

然后使用dict理解转换为字典。

result = { tup[0]:tup[1:] for tup in map(None, EmployeeID_List, EmployeeFirstName_List, managerID_List, managerFirstName_List) }

结果:

>>> result {555: ('e', None, None), 444: ('d', None, None), 333: ('c', 666, 'h'), 222: ('b', 777, 'g'), 111: ('a', 888, 'f')}

注意:结果是元组的字典。如果您需要列表,请将tup[1:]替换为list(tup[1:])

答案 3 :(得分:0)

'''
OP has four lists. He wants EmployeeID_List to serve to serve
as the keys in the dict, and he wants the rest of the lists to
serve as the values in the dict key-value pairs. If the indices
in the other lists don't match up, he wants 'Null', or 'NaN'.
'''
#Create the empty dictionary 
Employee_ManagerDic = {}

#Create the EmployeeID_List
EmployeeID_List = [111, 222, 333, 444, 555]

#Create the EmployyeFirstName_List
EmployeeFirstName_List = ['a', 'b', 'c', 'd', 'e']

#Create the managerID_List
managerID_List = [888, 777, 666]

#Create the managerFirstName_List
managerFirstName_List = ['f', 'g', 'h']

#Create a variable to increment the indicies 
num = -1

#Create another variable to increment the indices 
other_num = -1

#Run a for loop loop for EmployeeID_List
#Make the 'item' the dict key
#Make the value the EmployeeFirstName that corresponds
for item in EmployeeID_List:
      num += 1
      Employee_ManagerDic[item] = list(EmployeeFirstName_List[num])


#Check to see if the indicies match in the lists 
how_many_indicies = len(EmployeeID_List) - len(managerID_List)
how_many_indicies2 = len(EmployeeID_List) - len(managerFirstName_List)

#Print the difference in the indicies 
print(how_many_indicies)
print(how_many_indicies2)

#If the indicies don't match, fill the empty space with 'Null'
managerID_List.append('Null')
managerID_List.append('Null')
managerFirstName_List.append('Null')
managerFirstName_List.append('Null')

#Append the values in the other lists to the dictionary lists 
for value in Employee_ManagerDic.values():
       other_num += 1
       value.append(managerID_List[other_num])
       value.append(managerFirstName_List[other_num])

print(Employee_ManagerDic)

这是输出:

{111: ['a', 888, 'f'], 222: ['b', 777, 'g'], 333: ['c', 666, 'h'], 444: ['d', 'Null', 'Null'], 555: ['e', 'Null', 'Null']}

这里我创建了num和other_num之类的变量,这样在for循环期间,每次运行循环时,我们都可以将列表的索引递增+ = 1。我根据您的请求将字典键设置为EmployeeID_List中项的值,然后将该值设置为EmployeeFirstName_List。我将要添加的索引从EmployeeFirstName_List增加为值,并使用' list'函数将其转换为我们创建的字典中的嵌套列表。之后,我注意到您的其他列表中的索引较少,因此如果您正在运行用户可能缺少数据的程序,我决定获取其他列表的长度并将它们与EmployeeID_List的长度进行比较。如果它们的长度不同,我会附加“Null'到列表的末尾。我将Null追加到列表末尾的次数取决于它们缺少多少个索引。最后,对于字典中的每个值,我们将另外两个列表的列表项追加到字典列表中。我根据它们的索引附加它们,并且每次通过列表增加索引。当我们打印结果时,我们得到您需要的输出。

答案 4 :(得分:0)

如果您能在脑海中想象输出,那就很容易了。 假设您有三个列表变量,并且您想为它们提供标题(标签)并创建一个字典变量。我们通过一个例子来说明。

Zipcodes = ['98732','66786','34759']
latitude = ['1.5', '5.6', '3.4']
longitude = ['100.10', '112.4','140.76']
headers = ['Zip Codes', 'latitude', 'longitude']
info = []
info.append(Zipcodes)
info.append(latitude)
info.append(longitude)
Dic = dict(zip(headers, info))
print(Dic)

如您所见,我们将所有信息放在一个列表中,其中包含其他三个列表变量。然后我们使用“dict”函数压缩标签和信息,它会给我们字典变量。输出将是:

{'Zip Codes': ['98732', '66786', '34759'], 'latitude': ['1.5', '5.6', '3.4'], 'longitude': ['100.10', '112.4', '140.76']