[英]Append multiple value in Dictionary values with same key
我想 append 字典中具有相同鍵的多個值。
mydict={'dd6729': np.array([-0.06136101]),
'941a60': np.array([-0.03989978])}
所需的 Output:
{'dd6729': [array([-0.06136101]),array([-0.06136101])], '941a60': [array([-0.03989978]),array([-0.06136101])]}
我試過這樣的事情:
for i,v in mydict.items():
mydict[i].append(v)
print(mydict)
但有錯誤
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-398-fbc8d90525de> in <module>
1 for i,v in mydict.items():
----> 2 mydict[i].append(v)
3 print(mydict)
4
AttributeError: 'numpy.ndarray' object has no attribute 'append'
由於值是 Numpy 數組,所以我無法 append。
您在字典中的值對於不同的鍵並不一致,您以后可能會遇到問題。 為什么不首先將其定義為列表? 像這樣:
mydict={'dd6729': [np.array([-0.06136101])],
'941a60': [np.array([-0.03989978])]}
稍后,如果您對這些值進行任何進一步的處理,則讀取和處理這些值會容易得多。
The problem is that mydict[i]
is a numpy.ndarray
so to append to it you either need to use the numpy.append
function, or use a regular list instead.
for i,v in mydict.items():
mydict[i] = np.append(mydict[i], v)
print(mydict)
附言
我不知道這是否是您的意思,但 output 變為:
{'dd6729': array([-0.06136101, -0.06136101]), '941a60': array([-0.03989978, -0.03989978])}
而不是您想要的 output ( '941a60'
中的第二項)。
你應該使用這個問題的defaultdict
from collections import defaultdict
mydict={'dd6729': np.array([-0.06136101]),
'941a60': np.array([-0.03989978])}
new_dict=defaultdict(list)
for i,v in mydict.items():
new_dict[i].append(v)
print(new_dict)
創建一個新的 Python 列表並替換舊值:
mydict={'dd6729': np.array([-0.06136101]),
'941a60': np.array([-0.03989978])}
for i,v in mydict.items():
mydict[i] = [v, v]
print(mydict)
出去:
{'dd6729': [array([-0.06136101]), array([-0.06136101])], '941a60': [array([-0.03989978]), array([-0.03989978])]}
在 mydict[i].append(v) 中,mydict[i] 是一個 numpy 數組,它沒有屬性 append。
如果想要 append 到 numpy 數組,可以使用 np.append。 IE
for i,v in mydict.items():
mydict[i] = np.append(mydict[i], v)
將字典值轉換為列表,然后將 append 轉換為另一個數組值后,它會給出所需的 output。
from collections import defaultdict
mydict={'dd6729': np.array([-0.06136101]),
'941a60': np.array([-0.03989978])}
new_dict=defaultdict(list)
for i,v in mydict.items():
new_dict[i].append(v)
for i,v in new_dict.items():
new_dict[i].append(v[0])
Output:
defaultdict(list,
{'dd6729': [array([-0.06136101]), array([-0.06136101])],
'941a60': [array([-0.03989978]), array([-0.03989978])]})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.