我正在尝试在python中创建一个函数,以使用自定义名称创建字典。到目前为止,我正在使用的代码如下:
def PCreate(P):
P = {}
print('Blank Party Created')
我遇到的问题是,无论何时我使用该函数,无论我为P设置什么,
PCreate('Party1')
它将创建一个名为“ P”的空白字典。有没有办法让它创建一个名为Party1的字典?
答案 0 :(得分:2)
It looks like you're confused with how variable names, and strings, and objects interact withing Python. When you have the function PCreate(P)
you are saying that when the function is called, it will take on parameter, and within the function that parameter will be called P. This means that if you have the function,
def func(P):
print(P)
and call it three times,
func('two words')
func(4)
func([3, 'word'])
you will get the output:
two words
4
[3, 'word']
This is because the parameter P
has no explicit type in Python. So, when you called your function with the argument 'Party1'
the values looked like this
def PCreate(P):
# P is currently 'Party1'
P = {}
# P no longer is Party1, and now references {}
...
So you didn't assign {}
to the variable with the name Party1
, you overwrote the local variable P with a new empty dict.
I think you probably do not want to be doing what you're doing, but see this answer for more information on setting a variable using a string variable as its name.
What I recommend you do is create a function that returns your custom dictionaries, and assign the returned value to your custom name.
def new_custom_dict():
my_dict = {} # Pretend this is somehow custom
return my_dict
Party1 = my_custom_dict()
If you need the reference key to your new dictionary to be stored in a string, then you're in luck because that's what dictionaries are for!
You can first create a dictionary that will be used to store your custom named dictionaries:
dictionaries = {}
and when you want to add a new dictionary with a custom name, call this function
def insert_new_dictionary(dictionaries, dictionary_name):
dictionaries[dictionary_name] = {}
e.g.
insert_new_dictionary(dictionaries, 'Party1')
insert_new_dictionary(dictionaries, 'Party2')
would leave you with two dictionaries accessible by dictionaries['Party1']
and dictionaries['Party2']