📜  Python – 列表中的自定义字典初始化

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

Python – 列表中的自定义字典初始化

在使用Python时,我们可能会遇到需要使用自定义字典初始化特定大小的列表的问题。此任务在 Web 开发中用于存储记录。让我们讨论可以执行此任务的某些方式。

方法 #1:使用{dict} + "*" operator
可以使用“*”运算符执行此任务。我们可以创建一个包含单个自定义字典的列表,然后将其乘以列表大小的 Number。缺点是会生成类似的参考字典,这些字典将指向类似的内存位置。

# Python3 code to demonstrate working of
# Custom dictionary initialization in list
# using {dict} + "*" operator
  
# Initialize dict 
test_dict = {'gfg' : 1, 'is' : 2, 'best' : 3}
  
# Custom dictionary initialization in list
# using {dict} + "*" operator
res = [test_dict] * 6
  
print("The list of custom dictionaries is : " + str(res))
输出 :
The list of custom dictionaries is : [{'gfg': 1, 'best': 3, 'is': 2}, {'gfg': 1, 'best': 3, 'is': 2}, {'gfg': 1, 'best': 3, 'is': 2}, {'gfg': 1, 'best': 3, 'is': 2}, {'gfg': 1, 'best': 3, 'is': 2}, {'gfg': 1, 'best': 3, 'is': 2}]

方法#2:使用 {dict} + 列表推导
这也许是执行此任务的更好和正确的方法。我们用字典初始化列表的每个索引,这样,我们就有了独立引用的字典,而不是指向单个引用。

# Python3 code to demonstrate working of
# Custom dictionary initialization in list
# using {dict} + list comprehension
  
# Initialize dict 
test_dict = {'gfg' : 1, 'is' : 2, 'best' : 3}
  
# Custom dictionary initialization in list
# using {dict} + list comprehension
res = [test_dict for sub in range(6)]
  
print("The list of custom dictionaries is : " + str(res))
输出 :
The list of custom dictionaries is : [{'gfg': 1, 'best': 3, 'is': 2}, {'gfg': 1, 'best': 3, 'is': 2}, {'gfg': 1, 'best': 3, 'is': 2}, {'gfg': 1, 'best': 3, 'is': 2}, {'gfg': 1, 'best': 3, 'is': 2}, {'gfg': 1, 'best': 3, 'is': 2}]