[英]Getting specific data from list of dictionaries in Python using dot notation
我有这样的字典和字符串列表:
listDict = [{'id':1,'other':2}, {'id':3,'other':4},
{'name':'Some name','other':6}, 'some string']
我想通过点运算符从字典中列出所有ID(或其他属性)。 因此,从给定的列表中,我会得到列表:
listDict.id
[1,3]
listDict.other
[2,4,6]
listDict.name
['Some name']
谢谢
python不能这样工作。 您必须重新定义listDict
。 内置列表类型不支持这种访问。 更简单的方法就是像这样获取新列表:
>>> ids = [d['id'] for d in listDict if isinstance(d, dict) and 'id' in d]
>>> ids
[1, 3]
PS您的数据结构似乎非常异构。 如果您解释您要做什么,则可以找到更好的解决方案。
为此,您需要基于列表创建一个类:
class ListDict(list):
def __init__(self, listofD=None):
if listofD is not None:
for d in listofD:
self.append(d)
def __getattr__(self, attr):
res = []
for d in self:
if attr in d:
res.append(d[attr])
return res
if __name__ == "__main__":
z = ListDict([{'id':1, 'other':2}, {'id':3,'other':4},
{'name':"some name", 'other':6}, 'some string'])
print z.id
print z.other
print z.name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.