How to process multidimension array using Python?

I would like to process a multidimensional array.

Here is my array:

DefaultName = ["AB", "BC", "CD"]
DefaultCode = ["1D", "2D", "3D"]

Name = ["AB", "BC", "CD"]
Code = ["11","12", "13"]

from those arrays above, each DefaultName value belongs to DefaultCode value. For example,

DefaulCode "1D" belongs to DefaultName "AB" and so on.

For Array Name and Code as well. Each value of Code belongs to Name.

Code "11" belongs to Name "AB" and so on.

My problem is when the length of Code is different with length of Name. This is the case:

Name = ["AB", "BC", "CD"]
Code = [None ,"12", "13"]

The value of AB is none. So I need to looking for the Code for the Name that empty from DefaultCode by mapping the Name.

In that case, my expectation, AB will has Code from DefaultCode which is 1D because 1D DefaultName is the same as Name of the code.

I tried this, but I am stuck in the part to mapping which Name that empty code and how to looking for DefaultCode.

if (len(Name)) == (len(Code)):
    print("There is no empty code")
else:
    print("There is empty code")
    # looking for the Name that does not has code

    # after know which name that without code, then looking for the code from Default Code by mapping the Name

Anyone can help me please. I really appreciated for the help. Thank you so much. Gbu

Answer

You can do a dict lookup if the code is empty.

Ex:

DefaultName = ["AB", "BC", "CD"]
DefaultCode = ["1D", "2D", "3D"]

DefaultCode = dict(zip(DefaultName, DefaultCode)) # --> {'AB': '1D', 'BC': '2D', 'CD': '3D'}

Name = ["AB", "BC", "CD"]
Code = [" ","12", "13"]

res = {n: c if c.strip() else DefaultCode.get(n, "N/A") for n, c in zip(Name, Code)}
print(res)

Output:

{'AB': '1D', 'BC': '12', 'CD': '13'}

Leave a Reply

Your email address will not be published. Required fields are marked *