当前位置: 动力学知识库 > 问答 > 编程问答 >

django - How to create this nested python dictionary?

问题描述:

This is the what-I-want ( warning: Python noob here, this might be an incorrect way of representing, but I hope you get what I want )

forms = {

{ 'id' : '1',

'form' : form_something,

},

{ 'id' : '4',

'form' : form_something2,

}

}

Now my question is how do I create this dictionary in my django view which goes like this, so far->

links = Links.objects.all()

forms = {}

for link in links:

form = LinkForm(instance = link )

forms.update({ 'id' : link.id, 'form' : form})

# which is obviously the wrong way to do it

网友答案:

This will create a list of dictionaries:

links = Links.objects.all()
forms = []
for link in links:
    form = LinkForm(instance = link)
    forms.append({'id': link.id, 'form': form})

If you want to create a dictionary of dictionaries, you have to have keys:

links = Links.objects.all()
forms = {}
for link in links:
    form = LinkForm(instance = link)
    # you need something to use as a key
    forms[key] = {'id': link.id, 'form': form}

Notice I changed where you had spaces in your code to match the standard Python way, but it doesn't really matter.

The form of the nested dictionary would be:

forms = { 
       'key1': { 'id' : '1',
          'form' : form_something,
        },
       'key2': { 'id'  : '4',
          'form' : form_something2
        }
    }  

I added keys and removed the comma from after form_something2.

网友答案:

I've never worked with django, but in pure python, it'd go something like (you want a list/tuple of forms, not a dictionary of forms):

links = Links.objects.all()
forms = []
for link in links:
  form = LinkForm(instance = link)
  # the comma tells python to treat the contents inside the ( ) as a list
  forms.append({ 'id' : link.id, 'form' : form })

EDIT:

Based on the discussion in the comments, lists are a better option in comparison to tuples in terms of performance. Edited the code above to reflect this change.

网友答案:

i think what you want to do is something like this:

forms = { '1': form_something,
      '4':form_something2,
     }

This way you will look for your forms with their id (which is a common way to find things)

you can do this this way:

forms = {}

for link in Links.objects.all():
    form = LinkForm(instance = link )
    forms[form.id] = form`

Now I am curious why you want to save forms in a dictionary? seems odd to me.

Hope this helps

分享给朋友:
您可能感兴趣的文章:
随机阅读: