[英]How to create a nested dictionary from existing dictionary with set and list of tuples
我已經解析了一個 midi 文件,並且我已經成功地得到了一個按樂器分解的音符字典。 一個簡短的例子是下面的note_dict
,為了這個問題的目的而被截斷。
我的最終目標是擁有一個嵌套字典,為我提供曲目名稱,然后將每個可能的音符作為鍵,然后將所有可能的“下一個”音符列表作為值。 目的是將其用作Foxdot 中的馬爾可夫鏈,這是一個用於音樂生成的 python 接口。
它應該看起來像:
{'track1': {note: [note1, note2, note3], note2: [note1, note2, note3]}, 'track2': {note: [note1, note2, note3], note2: [note1, note2, note3]}
這是我所擁有的一個例子:
import itertools
def pairwise(iterable):
a, b = itertools.tee(iterable)
next(b, None)
return list(zip(a, b))
note_dict = {'Vocal': [-2, -2, -1, -2], 'Guitar': [1, 1, 4, 1, -2, 1]}
note_dict_updated = { track: [{ n for n in notes }, pairwise(notes), notes] for track, notes in note_dict.items() }
print(note_dict_updated)
這給了我以下內容,其中第一組是所有不同的音符,元組列表是(note, next note)
的配對,最后一個列表只是按順序排列的原始音符列表。
{'Vocal': [{-2, -1}, [(-2, -2), (-2, -1), (-1, -2)], [-2, -2, -1, -2]], 'Guitar': [{1, 4, -2}, [(1, 1), (1, 4), (4, 1), (1, -2), (-2, 1)], [1, 1, 4, 1, -2, 1]]}
我希望集合的元素充當鍵,並且當元組的第一個元素與集合的元素匹配時,它被添加到與鍵關聯的值列表中。
根據上面的note_dict
,我想要的最終結果是:
{'Vocal': {-2: [-2, -1], -1: [-2]}, 'Guitar': {1: [1, 4, -2], 4: [1], -2: [1]}}
盡管如此,我並沒有被鎖定在我需要使用note_dict_updated
的方法中。 如果有更聰明的方法可以從note_dict
獲得我想要的最終結果,我很想聽聽。
編輯:我已經更新了我的問題。 第一個答案適用於我的初始示例,但我相信當每個值中的注釋列表重疊時會出現問題。 希望我更新后的預期最終結果會更有幫助。
第一個循環創建具有內部鍵和相同唯一集的字典的中間字典。 然后使用第二個 for 循環對其進行清理,如下所示:
輸入:
{'Vocal': [-2, -2, -1, -2], 'Guitar': [1, 1, 4, 1]}
Output:
{'Guitar': {1: [1, 4], 4: [1]}, 'Vocal': {-2: [-1, -2], -1: [-2]}}
代碼:
#create a new dictionary of dictionary with inner keys and same unique sets
note_dict_updated={}
for key, value in note_dict.iteritems():
note_dict_updated[key]={}
for element in set(note_dict[key]):
note_dict_updated[key][element]=list(set(note_dict[key]))
# remove the values (of not interest) from list values of inner keys
for key, value in note_dict_updated.iteritems():
comb=[]
for lkey, lvalue in note_dict_updated[key].iteritems():
for val in lvalue:
if (val,lkey) in comb:
try:
note_dict_updated[key][lkey].remove(lkey)
except ValueError as e:
print ('Issue in key {} for subkey {}'.format(key,lkey))
for val in lvalue:
comb.append((lkey,val))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.