0

I have a dictionary in python that I created from a JSON file. Now, I need to pass its values to insert into a postgresql database.

dictionary

if(i['trailers']):
    a = [
        {'url': i['images'][0]['url'], 'type': i['images'][0]['type']},
        {'url': i['images'][1]['url'], 'type': i['images'][1]['type']},
        {'url': i['trailers'][0]['url'], 'type': 'Trailer'},
        {'url': i['trailers'][1]['url'], 'type': 'Trailer'},
    ]
else:
    a = [
        {'url': i['images'][0]['url'], 'type': i['images'][0]['type']},
        {'url': i['images'][1]['url'], 'type': i['images'][1]['type']},
    ]
length = len(a)

Here, I created the dictionary. If there is anything inside the trailer it goes A, else it goes B. In the B case, trailers doesn't exists. Then I get the length of the dictionary.

Now, I will try to insert these elements into the table media, that depends on movies. Their relation is movie(1):media(n).

INSERT INTO media

for x in range(length):
    query = ("""INSERT INTO media VALUES (%s, %s, %(url)s, %(type)s);""")
    data = (media_id, media_movie_id)
    cur.execute(query, data)
    conn.commit()
    media_id += 1

Here is what I'm trying to do. Since movie can have many media, I'll create a for to move through all the elements and inserting them in the table. With their id being incremented.

The problem is, I don't know how to do this quiet right in Python, since I always create a query and a data and then cur.execute it and the example that I got, was a entire dictionary being used, without any other kind of value.

1 Answer 1

0

So, if anyone have this kind of problem, the solution is simple, actually.

I remade my dict in something like this:

i['trailers'] = i.get('trailers') or []
dictionary = [{'url': x['url'], 'type': x['type']} for x in i['images'] + i['trailers']]

This solution was made by @minboost here

Then, for the insertion, is something like that:

for i, dic in enumerate(dictionary):
    query = ("""
        INSERT INTO media (id, movie_id, url, type)
        VALUES (%s, %s, %s, %s);
        """
    )
    data = (media_id, media_movie_id, dictionary[i]['url'], dictionary[i]['type'])
    cur.execute (query, data)
    conn.commit()

All working perfectly. :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.