简体   繁体   中英

Retrieving data from a Python Tuple

I am trying to retrieve and reuse data from a JSON object in a for loop in Python. An example of a single JSON object below:

{
    "id": "123456789",
    "envs": [
        "env:remote1",
        "env:remote2",
        "env:remote3"
    ],
    "moves": {
        "sequence1": "half glass full",
        "sequence2": "half glass empty"
    }
}

For loop example

for i in ids:
    print(i["envs"])
    print(i["moves"])

envs will be successfully printed since it is a list. However, since moves is a tuple I receive a KeyError as it is looking for a key in a dictionary. What is the Python recommended way of pulling data from a tuple in this instance. For example, I want to print sequence1 or sequence2 .

Thanks

It appears you made a typographic error.

From this code

ids = [
    {
        "id": "123456789",
        "envs": [
            "env:remote1",
            "env:remote2",
            "env:remote3",
        ],
        "moves": {
            "sequence1": "half glass full",
            "sequence2": "half glass empty",
        },
    }
]
for i in ids:
    print(i["envs"])
    print(i["moves"])

I obtain these results

['env:remote1', 'env:remote2', 'env:remote3']
{'sequence1': 'half glass full', 'sequence2': 'half glass empty'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM