我想從參考字典“fulltracks”中查找值(“uri”)并創建一個具有更新值的新字典。之后,每個串列都將用于使用 spotify API 創建播放串列。
考慮這個字典串列,每個串列項都顯示一個曲目:
fulltracks = [{"artists":[1,2], "uri": "xyz",}
{"artists":[3], "uri": "abc"},
{"artists":[4], "uri": "nmk"},
{"artists":[5], "uri": "qwe"},
此外,我有這本字典,其中的值是來自 fulltracks 的鍵(藝術家):
genres = {
"rock": [1],
"pop": [2],
"hip hop": [3,4],
"rap": [4],
"house": [5]}
我想出現在字典“genres_uris”的更新版本中:
genres_uris = {
"rock": ["xyz"],
"pop": ["xyz"],
"hip hop": ["abc", "nmk"],
"rap": ["abc"],
"house": ["qwe"]}
我將其稱為 Excel 中的查找,但無法深入了解 Python 方法/搜索的正確關鍵字。我為此遇到了熊貓,這個庫是解決我問題的正確方法嗎?
uj5u.com熱心網友回復:
您可以使用字典理解:
>>> {k: [d["uri"] for d in fulltracks for val in v if val in d["artists"]] for k, v in genres.items()}
{'rock': ['xyz'],
'pop': ['xyz'],
'hip hop': ['abc', 'nmk'],
'rap': ['nmk'],
'house': ['qwe']}
uj5u.com熱心網友回復:
對于此類作業,我建議您查看pandas,這是一個資料分析 Python 庫,您也可以像 Excel on steroids 和 Python 一樣考慮使用它。https://pandas.pydata.org/
但沒有它也是可行的。一種可能的方法是將您的fulltracks串列轉換為artist_id -> uri映射:
artist_to_uri = {artist: fulltrack["uri"] for fulltrack in fulltracks for artist in fulltrack["artists"]}
# {1: 'xyz', 2: 'xyz', 3: 'abc', 4: 'nmk', 5: 'qwe'}
genres_uris然后生成映射很簡單:
{
genre: [artist_to_uri[artist] for artist in artists]
for genre, artists in genres.items()
}
# {'rock': ['xyz'],
# 'pop': ['xyz'],
# 'hip hop': ['abc', 'nmk'],
# 'rap': ['nmk'],
# 'house': ['qwe']}
uj5u.com熱心網友回復:
我嘗試將其應用于“真實”的完整曲目。我無法使結構正常作業。
全軌看起來像這樣:
[Fulltracks = FullTrack with fields:
album = SimpleAlbum(album_group, album_type, artists, ...)
artists = [2 x SimpleArtist(external_urls, href, id, name, type, uri)
uri = 8192118xq9101a?1],
[Fulltracks = FullTrack with fields:
album = SimpleAlbum(album_group, album_type, artists, ...)
artists = [3 x SimpleArtist(external_urls, href, id, name, type, uri)
uri = 121212a0xa?1?1010]
例如,我可以使用以下方法訪問第一個串列項的第一位藝術家:
fulltracks[0].artist[0].id
你知道如何調整你推薦的代碼片段嗎?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/473207.html
