简体   繁体   English

Python 根据从列表中读取的值创建多个字典

[英]Python create multiple dictionaries from values ​read from a list

I have the following list of values: Numbers = [1,2,3,4].我有以下值列表:Numbers = [1,2,3,4]。 Is it possible to create a dictionary with the same name as the values contained in the list?是否可以创建与列表中包含的值同名的字典?

Example: dictionary_1 = {} dictionary_2 = {}.... dictionary_Number.. {}示例:dictionary_1 = {} dictionary_2 = {}.... dictionary_Number.. {}

I would like to create these dictionaries automatically, without creating them manually, reading the numbers contained in the list我想自动创建这些字典,而不是手动创建它们,读取列表中包含的数字

You may use the keyword exec in python. Here is an example of your solution,您可以在 python 中使用关键字exec 。这是您的解决方案示例,

List = [1, 2,3]
for ele in List:
    dic = f"Dictionary_{ele}"
    exec(dic+" = {}")
print(Dictionary_1, Dictionary_2, Dictionary_3, sep='\n') 

you may use it according to you, but the disadvantage for it is that you will need to use exec every time you need to use it or you must know what would be the name outcome of the first use of exec ...你可以根据你的情况使用它,但它的缺点是你每次需要使用它时都需要使用exec或者你必须知道第一次使用exec的名称结果是什么......

I hope I helped...我希望我帮助...

Use the inbuild functions and remember that a dictionary needs a tuble (key & value):使用内置函数并记住字典需要一个小管(键和值):

Example-Code:示例代码:

Numbers = [1,2,3,4]
Numbers_dict = dict.fromkeys(Numbers,"dict_value")
print(Numbers_dict)

This will output:这将是 output:

{'1': 'dict_value', '2': 'dict_value', '3': 'dict_value', '4': 'dict_value'}

If you want to get a single dictonaries for each list-value, you first have to create for each list-value an empty variable.如果您想为每个列表值获取一个字典,您首先必须为每个列表值创建一个空变量。 After this you have to fill this empty vairables within a loop.在此之后,你必须在一个循环中填充这个空变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM