Getting specific data from list of dictionaries in Python using dot notation
I have a list of dictionaries and strings like so:
listDict = [{'id':1,'other':2}, {'id':3,'other':4},
{'name':'Some name','other':6}, 'some string']
I want a list of all the ids (or other attributes) from the dictionaries via dot operator. So, from the given list I would get the list:
listDict.i开发者_运维百科d
[1,3]
listDict.other
[2,4,6]
listDict.name
['Some name']
Thanks
python doesn't work this way. you'd have to redefine your listDict. the built-in list type doesn't support such access. the simpler way is just to get the new lists like this:
>>> ids = [d['id'] for d in listDict if isinstance(d, dict) and 'id' in d]
>>> ids
[1, 3]
P.S. your data structure seems to be awfully heterogeneous. if you explain what you're trying to do, a better solution can be found.
To do that, you'd need to create a class based on list:
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
加载中,请稍侯......
精彩评论