[英]Specifying Argument Type For List of Dictionary For a Python Function
I have a function whose argument is a list of dictionaries.我有一个 function 的参数是字典列表。 I am trying to specify the type of elements for the dictionary in the function argument.我试图在 function 参数中指定字典的元素类型。 The dictionary has the following form:字典有以下形式:
{'my_object':my_object, 'data':int}
my_object
is a custom datatype. my_object
是自定义数据类型。 Is there any way to specify the type of dictionary, something like the one in below:有没有办法指定字典的类型,如下所示:
def my_function(x : list[dict[my_object, int]]):
Python complains about how I defined the type and gives me the following error: Python 抱怨我如何定义类型并给我以下错误:
TypeError: 'type' object is not subscriptable
You can try this:你可以试试这个:
from typing import List, Dict
def get_list_of_dicts(name: str, surname: str) -> List[Dict]:
return [{'name': name, 'surname': surname}]
print(get_list_of_dicts('Frank', 'Zappa'))
I hope it is useful for you.我希望它对你有用。
If you are asking can you specify a list of dictionaries containing a custom object as keys, then the answer is below.如果您问是否可以指定包含自定义 object 作为键的字典列表,那么答案如下。 If you wish to specify more than one type of object as a key within the same dictionary though, this won't work.但是,如果您希望在同一个字典中指定一种以上类型的 object 作为键,这将不起作用。
You can do the former in Python 3.9 with type aliases.您可以在 Python 3.9 中使用类型别名执行前者。 Reference https://docs.python.org/3/library/typing.html gives example with list of dicts.参考https://docs.python.org/3/library/typing.html给出了示例列表。
Example below shows a list of dicts containing custom objects as keys.下面的示例显示了包含自定义对象作为键的字典列表。
from collections.abc import Sequence
class MyClass:
def __init__(self, arg1, arg2):
self.attr1 = arg1 + arg2
class AnotherClass:
def __init__(self, arg1, arg2):
self.attr1 = arg1 + arg2
seq1 = dict[MyClass, int]
seq2 = list[seq1]
def myfunc(arg1: Sequence[seq2]) -> seq2:
for dict in arg1:
for key, value in dict.items():
print(key.attr1, value)
#Correct type provided.
myobj1 = MyClass('A', '1')
myobj2 = MyClass('B','2')
listdict= [{myobj1: 10, myobj2: 20}, {myobj2: 100, myobj1: 200}]
listdict
myfunc(listdict)
#Incorrect type provided.
myobj1 = AnotherClass('A', '1')
myobj2 = AnotherClass('B','2')
listdict= [{myobj1: 10, myobj2: 20}, { myobj2: 100, myobj1: 200}]
myfunc(listdict)
A1 10
B2 20
B2 100
A1 200
Note: Linters may not recognize valid inputs though.注意:尽管 Linter 可能无法识别有效输入。 Eg mypy complains that the list of dict(object, int) is not a sequence thereof.例如 mypy 抱怨 dict(object, int) 的列表不是它的序列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.