简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM