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

使用点表示法从Python中的字典列表中获取特定数据,python,list,Python,List,我有一个字典和字符串列表,如下所示: 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 [

我有一个字典和字符串列表,如下所示:

    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不是这样工作的。您必须重新定义您的
列表dict
。内置列表类型不支持此类访问。更简单的方法是获得如下新列表:

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

另外,您的数据结构似乎非常异构。如果你解释一下你想做什么,就会找到更好的解决方案。

python不是这样工作的。您必须重新定义您的
列表dict
。内置列表类型不支持此类访问。更简单的方法是获得如下新列表:

>>> ids = [d['id'] for d in listDict if isinstance(d, dict) and 'id' in d]
>>> ids
[1, 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

为此,您需要基于列表创建一个类:

    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

为什么?这不是正确的Python语法。要点是什么?@s.洛特:所提供的代码中没有语法错误,并且可以通过各种技术(例如,通过
。\uuu getattr\uuu()
)轻松实现这种类型。但是为什么呢?这个用例是什么?为什么不创建一个类或命名元组呢?为什么要用字典来做这件事?@S.洛特:我怎么知道,OP为什么要这么做,他的用例是什么?我只指出了如何做到这一点,如果有人愿意的话,可以使用适当的标准Python语法为什么?这不是正确的Python语法。要点是什么?@s.洛特:所提供的代码中没有语法错误,并且可以通过各种技术(例如,通过
。\uuu getattr\uuu()
)轻松实现这种类型。但是为什么呢?这个用例是什么?为什么不创建一个类或命名元组呢?为什么要用字典来做这件事?@S.洛特:我怎么知道,OP为什么要这么做,他的用例是什么?我只指出了如何做到这一点,如果有人愿意的话,可以使用适当的标准Python语法