📜  Python – 使用自定义值列表初始化字典

📅  最后修改于: 2022-05-13 01:55:35.729000             🧑  作者: Mango

Python – 使用自定义值列表初始化字典

在Python中,通常会遇到必须使用字典来存储列表的情况。但在这些情况下,通常会检查第一个元素,然后在它出现时创建一个与键对应的列表。但它一直想要一种方法来初始化字典。带有自定义列表的键。让我们讨论实现这一特定任务的某些方法。

方法#1:使用字典理解
这是进行此初始化的最常用的方法。在这种方法中,我们创建了编号。我们需要的键,然后在我们继续创建键时初始化自定义列表,以便于以后的附加操作而不会出错。

# Python3 code to demonstrate 
# Custom list dictionary initialization
# using dictionary comprehension
  
# initialize custom list 
cus_list = [4, 6]
  
# using dictionary comprehension to construct
new_dict = {new_list: cus_list for new_list in range(4)}
      
# printing result
print ("New dictionary with custom list as keys : " + str(new_dict))
输出 :
New dictionary with custom list as keys : {0: [4, 6], 1: [4, 6], 2: [4, 6], 3: [4, 6]}

方法 #2:使用fromkeys()
fromkeys() 可以通过指定额外的自定义列表作为参数以及需要作为字典键的元素范围来执行此操作。

# Python3 code to demonstrate 
# Custom list dictionary initialization
# using fromkeys()
  
# initialization custom list 
cus_list = [4, 6]
  
# using fromkeys() to construct
new_dict = dict.fromkeys(range(4), cus_list)
      
# printing result
print ("New dictionary with custom list as keys : " + str(new_dict))
输出 :
New dictionary with custom list as keys : {0: [4, 6], 1: [4, 6], 2: [4, 6], 3: [4, 6]}