Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
110 views
in Technique[技术] by (71.8m points)

python - Append multiple value in Dictionary values with same key

I want to append multiple values with same key in dictionary.

mydict={'dd6729': np.array([-0.06136101]),
        '941a60': np.array([-0.03989978])}

Desired Output:

{'dd6729': [array([-0.06136101]),array([-0.06136101])], '941a60': [array([-0.03989978]),array([-0.06136101])]}

I tried something like this :

for i,v in mydict.items():
    mydict[i].append(v)
print(mydict)

but got error

---------------------------------------------------------------------------
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'

As the values are Numpy array so I am unable to append.

question from:https://stackoverflow.com/questions/66062020/append-multiple-value-in-dictionary-values-with-same-key

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you should use defaultdict of this problem

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...