python - Pythonic way to parse list of dictionaries for a specific attribute? -
i want cross reference dictionary , django queryset determine elements have unique dictionary['name'] , djangomodel.name values, respectively. way i'm doing to:
- create list of dictionary['name'] values
- create list of djangomodel.name values
- generate list of unique values checking inclusion in lists
this looks follows:
alldbtests = dbp.test_set.exclude(end_date__isnull=false) #django queryset vctestnames = [vctest['name'] vctest in vcdict['tests']] #from dictionary dbtestnames = [dbtest.name dbtest in alldbtests] #from django model # compare tests in protocol in fortytwo's db protocol vc obsoletetests = [dbtest dbtest in alldbtests if dbtest.name not in vctestnames] newtests = [vctest vctest in vcdict if vctest['name'] not in dbtestnames] it feels unpythonic have generate intermediate list of names (lines 2 , 3 above), able check inclusion after. missing anything? suppose put 2 list comprehensions in 1 line this:
obsoletetests = [dbtest dbtest in alldbtests if dbtest.name not in [vctest['name'] vctest in vcdict['tests']]] but seems harder follow.
edit: think of initial state this:
# vcdict list of django models following true alldbtests[0].name == 'test1' alldbtests[1].name == 'test2' alldbtests[2].name == 'test4' dict1 = {'name':'test1', 'status':'pass'} dict2 = {'name':'test2', 'status':'pass'} dict3 = {'name':'test5', 'status':'fail'} vcdict = [dict1, dict2, dict3] i can't convert sets , take difference unless strip things down name string, lose access rest of model/dictionary, right? sets work here if had same type of object in both cases.
vctestnames = dict((vctest['name'], vctest) vctest in vcdict['tests']) dbtestnames = dict((dbtest.name, dbtest) dbtest in alldbtests) obsoletetests = [vctestnames[key] key in set(vctestnames.keys()) - set(dbtestnames.keys())] newtests = [dbtestnames[key] key in set(dbtestnames.keys()) - set(vctestnames.keys())]
Comments
Post a Comment