我有一个像这样的字典和字符串列表:
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]
附言您的数据结构似乎非常异构。如果您解释您正在尝试做什么,就可以找到更好的解决方案。
