【问题标题】:how to add four lists into one dictionary如何将四个列表添加到一个字典中
【发布时间】:2018-09-24 05:02:29
【问题描述】:

在 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 循环,但我不知道如何构造循环的逻辑。

谢谢

【问题讨论】:

  • 您准备好使用 pandas 解决方案了吗?

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


【解决方案1】:
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:]

row[1:] 是一个切片,以防你不熟悉它并想用谷歌搜索它。

【讨论】:

    【解决方案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

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

    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 构造函数。

    【讨论】:

    • * 是多余的,只要正常传递参数即可。还值得注意的是,这假设至少有一个列表与 ID 列表一样长。
    • 我认为确保 dict 值是列表而不是元组并不重要。
    • @AlexHall 同意了,我为此添加了一条注释。我只是为了匹配 OP 的输出。
    【解决方案3】:

    对于 Python2.7,您可以使用带有 None 的 map 而不是 zip,这将为您提供最长的 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)]

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

    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:])

    【讨论】:

      【解决方案4】:
      '''
      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 附加到列表末尾的次数取决于它们缺少多少索引。最后,对于字典中的每个值,我们将其他两个列表的列表项附加到字典列表中。我根据它们的索引附加它们,并且每次通过列表递增索引。当我们打印结果时,我们会得到您需要的输出。

      【讨论】:

        【解决方案5】:

        如果你能在脑海中想象输出,这很容易。 假设你有三个列表变量,你想给它们标题(标签)并创建一个字典变量。让我们通过一个示例来说明它。

        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']
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-05-22
          • 1970-01-01
          • 2020-09-13
          • 1970-01-01
          相关资源
          最近更新 更多