Home > Blockchain >  Can't Print array element names (python)
Can't Print array element names (python)

Time:11-14

I have an array of points and I'm looking to print the name of the points instead of the actual points.

A = (2,0)

B = (3, 4)

C = (5, 6)

array1 = [A , B, C]

when I do print(array1[0]) it ends up printing the values. But I want to print the letters such as A, B or C. How would I print the letters instead?

I've also tried print(array1) and it also just prints all the values instead.

CodePudding user response:

A variable doesn't usually contain its own name. This is simply something you can use to target whatever value that is being referenced.

Obviously, the best answer will be related to the really why you want to print "A". If you just want to print the letter "A", then simply do:

print("A")

Obviously, that doesn't scale well depending on the reason why you want to print the name of the variable.

Instead, why don't you use a dictionary? A dictionary is a structure that contains a list of keys that each reference a different value.

dictionary = {"A": (2, 0), "B": (3, 4), "C": (5, 6)}

You can reference each tuple by using the key instead of an index.

print(dictionary["A"])

Will return (2,0)

If you want to print the first value of "B", you simply do dictionary["A"][0].

Alright, now, for the good stuff. Let's say that you want to print all keys AND their values together, you can use the items() method like this:

for key, value in dictionary.items():
  print(f"{key}={value}")

What happens if that items() will return a generator of tuples that contains both the keys and their corresponding value. In this way, you And you can use both the key and the value to do whatever you want with them.

By the way, the f in front of the string tells python that this is a formatted string and will compute anything written in between curly brackets and include them as part of the string. In this case, the code written above will output the following:

A=(2,0)
B=(3,4)
C=(5,6)

CodePudding user response:

Try writing array1=["A", "B", "C"] instead of array1=[A, B, C]. A, B, and C are variables so they represent their value, if you want the letters A, B, and C you should use strings instead.

  • Related