下面是我的代码:
def formateUserData(FirstName = None, MiddleName = None, LastName = None, DOB = None, Gender = None):
formatedUserData = {}
dataFieldKeys = ['First Name', 'Middle Name', 'Last Name', 'DOB', 'Gender']
dataFieldValues = [FirstName, MiddleName, LastName, DOB, Gender]
for key, value in zip(dataFieldKeys, dataFieldValues):
if value: formatedUserData[key] = value
return formatedUserData
如您所见,关键字参数必须重复3次(第一次在第1行,第二次在第3行,第三次在第4行)。有没有一种方法可以做到同样的事情,而不只是存储一次关键字参数?如果可能的话,也许可以通过某种方式遍历关键字参数?顺便说一句,我不希望使用**kwargs。
也许这启发了你考虑数据类,我觉得这很方便
from dataclasses import dataclass, fields
from datetime import date
from typing import Literal, Optional
@dataclass
class User:
first_name: Optional[str] = None
middle_name: Optional[str] = None
last_name: Optional[str] = None
dob: Optional[date] = None
gender: Optional[Literal['male', 'female']] = None
def not_none_dict(user: User) -> dict:
not_none = {}
for field in fields(user):
value = getattr(user, field.name)
if value:
not_none[field.name] = value
return not_none
print(
not_none_dict(User(
first_name='Joe',
last_name='Doe'
))
)
>>> {'first_name': 'Joe', 'last_name': 'Doe'}
在我看来,最短的解决方案是使用locals():
def formateUserData2(FirstName = None, MiddleName = None, LastName = None, DOB = None, Gender = None):
return {k:v for k,v in locals().items() if v}
但是这个解决方案没有考虑标签的更改,因此需要绑定
def formateUserData(FirstName = None, MiddleName = None, LastName = None, DOB = None, Gender = None):
binding = {'First Name':FirstName,
'Middle Name':MiddleName,
'Last Name':LastName,
'DOB':DOB,
'Gender':Gender}
return {k:v for k,v in binding.items() if v}
使用显式绑定是一个很好的实践,因为它明确了你的期望是什么。