Reputation: 81
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
Upvotes: 0
Views: 69
Reputation: 20550
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'}
Upvotes: 1