Home > Back-end >  How to add a value into an array value in dictionary in python
How to add a value into an array value in dictionary in python

Time:10-08

Given:

 a={'sex': [[0.1834862385321101], [0.8165137614678899], [nan], [nan]], 
   'cp': [[0.7155963302752294], [0.08256880733944955], [0.1559633027522936]]}

I want to add a value into the value of an array which key equals to 'sex' to get an out put as follow:

a={'sex': [[0.1834862385321101, 1], [0.8165137614678899, 1], [nan], [nan]], 
    'cp': [[0.7155963302752294], [0.08256880733944955], [0.1559633027522936]]}

I tried to use update(), but it doesn't work.

CodePudding user response:

You could use: a['sex'][0].append(1)

output:

{'sex': [[0.1834862385321101, 1], [0.8165137614678899], [nan], [nan]],
 'cp': [[0.7155963302752294], [0.08256880733944955], [0.1559633027522936]]}

Similarly, a['sex'][1].append(1) for the other value

CodePudding user response:

This could another possible solution:

a={'sex': [[0.1834862385321101], [0.8165137614678899], [], []], 'cp': [[0.7155963302752294], [0.08256880733944955], [0.1559633027522936]]}

for lst in a.get('sex', []):
    if lst:
        lst.append(1)

print(a)

Output:

{'sex': [[0.1834862385321101, 1], [0.8165137614678899, 1], [], []], 'cp': [[0.7155963302752294], [0.08256880733944955], [0.1559633027522936]]}
  • Related