Home > Software design >  Converting values of dictionary into array in the consecutive order (python)
Converting values of dictionary into array in the consecutive order (python)

Time:07-22

My objective is converting a dictionary of the label id and label name into an array in consecutive order same as the dictionary.

Here's codes and outcome from getting dict from a dataframe.

CODE:

classes_with_id = {id: labels for id, labels in zip(train['Human_CategoryID'], train['Human_Category'])}
classes_with_id

OUTCOME:

enter image description here

When I get values from the dict and put into an array I got this outcome.

Code:

classes_array = [label for label in classes_with_id.values()]
classes_array

Outcome:

enter image description here

You can see that the first index of the array is 'Call Center', and I would like to have 'Accessibility' as the first index of the array (same consecutive order of values in the dict)

How to make them in order same as the values in dictionary?

Thank you for your help.

CodePudding user response:

A solution found with these easy code:

  1. Create empty the string array based on the range of labels

classes_array = ["" for x in range(len(classes_with_id))]

  1. Put label ids-1 as the index of the array and make them equal to each label.
for id, label in classes_with_id.items():
  classes_array[id-1] = label

CodePudding user response:

You can try with this code:

a ={1:"assebility",2:"facility",3:"company brand",4:"staff",5:"product and sevid"}
lista =[]
for k,v in a.items():
    lista.append(v)
    
print(lista)

output:

['assebility', 'facility', 'company brand', 'staff', 'product and sevid']
  • Related