[英]More elegant way to separate a list of dict(s) based on a value from an identical key in each dict in a class
I get a return of a list of dict(s), from a program, that have the same key in each dict, I would like to set a class attribute list based on the :value in each. 我从程序中获得了一个字典列表的返回,每个字典在每个字典中具有相同的键,我想基于每个字典中的:value设置一个类属性列表。 The dict list can have multiple same values 字典列表可以具有多个相同的值
[
{"key":"value"},
{"key":"differentvalue"},
{"key":"value"},
{"key":"newValue"},
{"key":"newValue"}
]
now i have a class like this ` 现在我有一个像这样的课程
class DynamicAttributesFromDict:
def __init__(self, listed):
for i in range(len(listed)):
name = listed[i]["key"]
p = getattr(self, name, [])
p.append(listed[i])
setattr(self, name, p)
I have it this way so i can access certain lists of dicts by obj.newValue or obj.value etc. This is just an example the real dicts in the list are much more longer and created from a program. 我有这种方式,这样我就可以通过obj.newValue或obj.value等访问某些字典列表。这只是一个示例,列表中的实际字典要更长,并且是由程序创建的。
Should I use hasattr first to check for the attribute and the getattr to append? 我应该首先使用hasattr来检查属性和要附加的getattr吗?
The above works, but it seems sketchy 以上工作,但似乎粗略
Kind of new to python classes, so any help would be appreciated python类的一种新东西,因此任何帮助将不胜感激
Edit: 编辑:
a better representation I think 我认为更好的表述
from pprint import pprint
listdict = [
{"key":"value", "difkey":"something"},
{"key":"differentvalue", "xkey":"yvalue"},
{"key":"value"},
{"key":"newValue"},
{"key":"newValue"}
]
class DynamicAttributesFromDict:
def __init__(self, listed):
for i in range(len(listed)):
name = listed[i]["key"]
p = getattr(self, name, [])
p.append(listed[i])
setattr(self, name, p)
f = DynamicAttributesFromDict(listdict)
pp(f.value)
pp(f.differentvalue)
pp(f.newValue)
filter(lambda x: x['key'] == 'value', my_data)
Outputs a generator object that turns into a list like this: 输出一个生成器对象,该对象变成如下列表:
[{'key': 'value'}, {'key': 'value'}]
Or we could do a list comprehension: 或者我们可以进行列表理解:
[d for d in my_data if d['key'] == 'value']
I'm rereading your question to make sure I answered it properly, and I'm not sure I did. 我正在重新阅读您的问题,以确保我已正确回答,但不确定是否已回答。 Let me know if you're looking for something else. 让我知道您是否正在寻找其他东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.