insert list of dictionary

73 views
Skip to first unread message

Tribo Eila

unread,
Oct 19, 2016, 9:15:21 AM10/19/16
to web2py-users
Hi,

supposed: 
db.define_table('color', Field('blue'),Field('yellow'),Field('red'))

COLORED_THINGS = {
    'blue': ['sky', 'jeans', 'powerline insert mode'],
    'yellow': ['sun', 'banana', 'phone book/monitor stand'],                  
    'red': ['blood', 'tomato', 'test failure']}

using db.color.insert(...). i'm trying to figure how to save in database base on key dict. i tried for loops but my head starts turning.

Scott Hunter

unread,
Oct 20, 2016, 9:11:52 AM10/20/16
to web...@googlegroups.com
Your fields are of type string (the default); so either make string representations of your lists or declare the fields as lists of strings.

Or, if you are trying to use this data to define *multiple* records, something like this might do what you want:

    for i in xrange(3):
        db.color.insert( blue=COLORED_THINGS['blue'][i],  yellow=COLORED_THINGS['yellow'][i],  red=COLORED_THINGS['red'][i] )

Anthony

unread,
Oct 20, 2016, 11:17:50 AM10/20/16
to web2py-users
On Wednesday, October 19, 2016 at 9:15:21 AM UTC-4, Tribo Eila wrote:
Hi,

supposed: 
db.define_table('color', Field('blue'),Field('yellow'),Field('red'))

COLORED_THINGS = {
    'blue': ['sky', 'jeans', 'powerline insert mode'],
    'yellow': ['sun', 'banana', 'phone book/monitor stand'],                  
    'red': ['blood', 'tomato', 'test failure']}

Do you want COLORED_THINGS to be a single record in the "color" table? If so, your fields will have to be of type "list:string" (so each field can store a list of strings) -- for example, Field('blue', 'list:string'). In that case, just do:

db.color.insert(**COLORED_THINGS)

Anthony
 

Tribo Eila

unread,
Oct 23, 2016, 7:52:39 AM10/23/16
to web2py-users
Perfect! 

Thank You very much.

Tribo Eila

unread,
Oct 23, 2016, 7:54:05 AM10/23/16
to web2py-users
Thank You Anthony.

You give me another idea...

Anthony

unread,
Oct 23, 2016, 2:22:32 PM10/23/16
to web2py-users
On Thursday, October 20, 2016 at 9:11:52 AM UTC-4, Scott Hunter wrote:
Your fields are of type string (the default); so either make string representations of your lists or declare the fields as lists of strings.

Or, if you are trying to use this data to define *multiple* records, something like this might do what you want:

    for i in xrange(3):
        db.color.insert( blue=COLORED_THINGS['blue'][i],  yellow=COLORED_THINGS['yellow'][i],  red=COLORED_THINGS['red'][i] )

If this is indeed what you want, then it would be better if you could structure the data as a list of dictionaries (instead of a dictionary with lists as its values):

COLORED_THINGS = [
   
{'blue': 'sky', 'yellow': 'sun', 'red': 'blood'},
   
{'blue': 'jeans', 'yellow': 'banana', 'red': 'tomato'}
]

And use .bulk_insert to create the records:

db.color.bulk_insert(COLORED_THINGS)

Anthony
Reply all
Reply to author
Forward
0 new messages