简体   繁体   English

一种更优雅的方法,根据值与类中每个字典中相同键的值分离字典列表

[英]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.

相关问题 如果键值的值是单独列表的成员,则无法有效地从字典中提取键 - Having trouble efficiently extracting key from a dict if key value's value is member of separate list 从Python中的字典中提取相同的键,值 - Extract identical key, value from a dict in Python 将dict列表转换为dicts字典的优雅方式 - Elegant way to transform a list of dict into a dict of dicts 如何基于Python中的匹配键将键值对添加到另一个字典列表中的现有字典列表中 - How to append key value pair to an existing list of dict from another list of dict based on matching Key in Python 通过拆分 python 列表中的每个项目填充的字典键和值 - Dict Key and Value populated from splitting each item in a python list 获取字典键的值作为列表(值是字典) - Getting a dict key's value as a list (the value is a dict) 根据键从Python的嵌套字典列表中获取值 - Get value from list of nested dict in Python based on key 有没有更优雅的方式来添加条件dict元素 - Is there a more elegant way to add conditional dict elements 从列表中生成字典的最快方法,其中键 == 值 - Fastest way to generate a dict from list where key == value 有没有办法从嵌套字典中访问一个值并根据搜索列表更新同一个字典中的值? - is there a way to access a value from a nested dict and update value in the same dict based on searching a list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM