Как я могу получить MySQL результатов в словарь, который можно искать по индексу? (в Python) - PullRequest
0 голосов
/ 19 апреля 2020

Я изучаю Python программирование для создания некоторых автоматизаций, часть сценария, который я создаю, выполняет итерации по объекту, я хочу иметь возможность искать те же элементы в БД MySQL, но не совсем уверен, как это сделать Итак.

Использование MariaDB учебник Я успешно получил нужные мне строки, однако я не уверен, как я могу искать элемент в списке cursor без необходимости вручную перебрать каждый результат.

Вот код, который у меня есть:

    cursor = mariadb_connection.cursor(dictionary=True)

    # here I get a list of items from an external service
    playlists = sp.user_playlists(username)
    # here I retrieve my playlists from a DB
    cursor.execute("SELECT id, name, monitor FROM playlists")
    rows = cursor.fetchall()
    while playlists:
        for i, playlist in enumerate(playlists['items']):
            print("%4d %s %s" % (i + 1 + playlists['offset'], playlist['id'],  playlist['name']))
            # while iterating through the playlists from the external service, I want to see if its included within my "rows" dictionary.

            key = "1"
            for row in rows:
                print("ID: {}, Name: {}, Monitor: {}".format(row['id'],row['name'], row['monitor']))

                # this does not work, there is an ID
                if key in rows:
                    print("found key")
                    break
                else:
                    print("NOT found key")


        if playlists['next']:
            playlists = sp.next(playlists)
        else:
            playlists = None

Я прокомментировал область, в которой мне нужна помощь.

1 Ответ

0 голосов
/ 19 апреля 2020

Сначала несколько комментариев. В вашем коде вы устанавливаете key на постоянную "1", которая никогда не меняется, и это не может быть правильным. rows, который возвращается из запроса, будет списком словарей. Оператор if key in rows: проверяет значение ключа не по ключам для каждого словаря, а по каждой строке, которая является целым словарем, и это неправильно. Это должно быть if key == row['id']:. Таким образом, пара изменений должна помочь:

cursor = mariadb_connection.cursor(dictionary=True)

# here I get a list of items from an external service
playlists = sp.user_playlists(username)
# here I retrieve my playlists from a DB
cursor.execute("SELECT id, name, monitor FROM playlists")
rows = cursor.fetchall()
# build a dictionary of keys:
id_dict = {row['id']: row for row in rows}
while playlists:
    for i, playlist in enumerate(playlists['items']):
        print("%4d %s %s" % (i + 1 + playlists['offset'], playlist['id'],  playlist['name']))
        # while iterating through the playlists from the external service, I want to see if its included within my "rows" dictionary.

        key = playlist['id'] # the key
        if key in id_dict:
            row = id_dict[key]
            print("ID: {}, Name: {}, Monitor: {}".format(row['id'],row['name'], row['monitor']))
            print("found key")
        else:
            print("NOT found key")

    if playlists['next']:
        playlists = sp.next(playlists)
    else:
        playlists = None

Другой, более эффективный способ

Не запрашивать изначально все списки воспроизведения из базы данных:

cursor = mariadb_connection.cursor(dictionary=True)

# here I get a list of items from an external service
playlists = sp.user_playlists(username)
# here I retrieve my playlists from a DB
while playlists:
    for i, playlist in enumerate(playlists['items']):
        print("%4d %s %s" % (i + 1 + playlists['offset'], playlist['id'],  playlist['name']))
        # while iterating through the playlists from the external service, I want to see if its included within my "rows" dictionary.
        id = playlist['id']
        cursor.execute("SELECT id, name, monitor FROM playlists where id = %s", (id,))
        row = cursor.fetchone() # this the match, if any
        if row:
            print("ID: {}, Name: {}, Monitor: {}".format(row['id'],row['name'], row['monitor']))
            print("found key")
        else:
            print("NOT found key")

    if playlists['next']:
        playlists = sp.next(playlists)
    else:
        playlists = None
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...