python - 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 return of list of dict(s), program, have same key in each dict, set class attribute list based on :value in each. dict list can have multiple same values

[     {"key":"value"},      {"key":"differentvalue"},      {"key":"value"},      {"key":"newvalue"},      {"key":"newvalue"} ] 

now have class `

class dynamicattributesfromdict:     def __init__(self, listed):         in range(len(listed)):             name = listed[i]["key"]             p = getattr(self, name, [])             p.append(listed[i])             setattr(self, name, p) 

i have way can access lists of dicts obj.newvalue or obj.value etc. example real dicts in list more longer , created program.

should use hasattr first check attribute , getattr append?

the above works, seems sketchy

kind of new python classes, appreciated

edit:

a better representation 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):         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 generator object turns list this:

[{'key': 'value'}, {'key': 'value'}] 

or list comprehension:

[d d in my_data if d['key'] == 'value'] 

i'm rereading question make sure answered properly, , i'm not sure did. let me know if you're looking else.


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -