0

Maybe a title is confusing but here is my problem.

I go through django model objects with nested for loop as below. In the end I want to have dictionary which has unique key value pairs.

Below code works but I don't feel that it's really efficient.

settings = []
for feature in features:
    for setting in feature.settings.all():
        settings.append({"name": setting.name, "active": setting.active})
return [dict(t) for t in {tuple(setting.items()) for setting in settings}]

so before return I am having something like this: [{'name': 'x', 'active': False}, {'name': 'y', 'active': True}, {'name': 'x', 'active': False}]

but when I return I remove duplicates in the list and return below. [{'name': 'x', 'active': False}, {'name': 'y', 'active': True}]

Sayse
  • 42,633
  • 14
  • 77
  • 146
Anisa Kollenhag
  • 103
  • 1
  • 8
  • sorry, you are right. it shouldn't be `settings` but only `setting.items`. i just edited. it's working now – Anisa Kollenhag Mar 24 '19 at 19:40
  • dictionaries have "unique key value pairs" by definition – joel Mar 24 '19 at 19:47
  • how do you want to define "unique"? which values do you want to keep/drop? – joel Mar 24 '19 at 19:50
  • well, what i want is this: for example I have `[{'name': 'x', 'active': False}, {'name': 'y', 'active': True}, {'name': 'x', 'active': False}` so in the end I should have list with 2 dictionaries as there is duplicated one – Anisa Kollenhag Mar 24 '19 at 20:02
  • perhaps `list(set(settings))` is all you need then – joel Mar 24 '19 at 20:17
  • Possible duplicate of [Removing duplicates in lists](https://stackoverflow.com/questions/7961363/removing-duplicates-in-lists) – joel Mar 24 '19 at 20:38

2 Answers2

1

If you're using postgres, you can use distinct with a fields attribute, and then use values, to get your settings as desired,

your code would be equivalent to:

feature.settings.distinct('name', 'active').values('name', 'active')
Sayse
  • 42,633
  • 14
  • 77
  • 146
0

You can use dictionary comprehension, if this is what you meant.

print({setting.name : setting.active for feature in features for setting in feature.settings.all()})

If the line gets too long, you can use something like this.

print({
    setting.name : setting.active
    for feature in features
    for setting in feature.settings.all()
})
Tigran Fahradyan
  • 399
  • 1
  • 4
  • 12