[英]How do I pass a new dictionary name as a parameter to a function in Python?
[英]how do I pass the name of a dictionary as an argument to my function
data = {'employer':'Apppe, Inc', 'title': 'Senior Software Engineer', 'manager': 'Steve Jobs', 'city': 'Cupertino'}
def my_function(**data):
employername = data['employer']
title = data['title']
manager = data['manager']
city = data['city']
print(city)
my_function(**data)
username = input("Enter dictionary name:")
my_function(**username)
如果我將文本數據輸入到輸入中。 我收到這個奇怪的錯誤。
Enter dictionary name:data
Traceback (most recent call last):
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
start(fakepyfile,mainpyfile)
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
exec(open(mainpyfile).read(), __main__.__dict__)
File "<string>", line 14, in <module>
TypeError: __main__.my_function() argument after ** must be a mapping, not str
[Program finished]
您可以使用locals()
函數獲取所有局部變量的字典,然后獲取用戶指定的局部變量。 像這樣:
data = {'employer':'Apppe, Inc', 'title': 'Senior Software Engineer', 'manager': 'Steve Jobs', 'city': 'Cupertino'}
def my_function(**data):
employername = data['employer']
title = data['title']
manager = data['manager']
city = data['city']
print(city)
my_function(**data)
username = input("Enter dictionary name:")
my_function(**(locals()[username]))
注意:小心使用此功能並始終清理用戶輸入,如果不這樣做的話。 那么你就可以讓自己接受注入攻擊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.