Home > Enterprise >  In Python: In a list of tuples that represent X, Y points, what is the syntax to access a particular
In Python: In a list of tuples that represent X, Y points, what is the syntax to access a particular

Time:02-25

For example if list = [{0: 1}, {0: 2}, {1: 0}, {1: 2}, {2: 0}, {2: 1}, {2: 2}]

what is the syntax to get the x and y of the second item?

x = list[1] ? y = list[1] ?

CodePudding user response:

The list you have shown is:

[{0: 1}, {0: 2}, {1: 0}, {1: 2}, {2: 0}, {2: 1}, {2: 2}]

This is a list of dicts, each with a single element. For the second item (at index 1), the dictionary has one key/value pair with key 0 and value 2. To access this, you could do this:

        myList = [{0: 1}, {0: 2}, {1: 0}, {1: 2}, {2: 0}, {2: 1}, {2: 2}]
        myDict = myList[1]
        key, value = next(iter(myDict.items()))
        print(key, value)

If what you want instead is a list of tuples, that would be something like:

[(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1), (2, 2)]

You could access the second tuple in the list as follows:

        myList = [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1), (2, 2)]
        x = myList[1][0]
        y = myList[1][1]
        print(x, y)

Alternatively, you could use this more concise assignment syntax:

        x, y = myList[1]
  • Related