使用点表示法从Python字典列表中获取特定数据

1 投票
2 回答
966 浏览
提问于 2025-04-16 10:36

我有一个包含字典和字符串的列表,像这样:

    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']

谢谢

2 个回答

3

要做到这一点,你需要创建一个基于列表的类:

    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
4

Python 不是这样工作的。你需要重新定义你的 listDict。内置的列表类型不支持那种访问方式。更简单的方法是这样获取新的列表:

>>> ids = [d['id'] for d in listDict if isinstance(d, dict) and 'id' in d]
>>> ids
[1, 3]

另外,你的数据结构看起来有点复杂。如果你能解释一下你想做什么,可能会找到更好的解决方案。

撰写回答