Сначала несколько комментариев. В вашем коде вы устанавливаете 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