You should probably use nested for loops.. what exactly you should print depends on how you expect your output to look.. but you could try this:
#!/usr/bin/env python3
import json
data = '{"297050": [[12, 137], [193, 776]], "297056": [[12, 203]]}'
data = json.loads(data)
for k, v in data.items():
print(k)
for list_of_ints in v:
for integer in list_of_ints:
print(integer)
Result:
297050
12
137
193
776
297056
12
203
Explanation:
We load in the sample json, and use items
to iterate over it's key value pairs. Now our keys are in k
and the outermost list is in v
. v
is a list, and a list of lists.. so we iterate that as list_of_ints
. And finally we loop over each of those lists, printing out the innermost integers as we go.
If what you want as your output is this:
For entry 297050 this is the list [12, 137], [193, 776] For entry 297056 this is the list [12, 203]
Then we can just modify the script a little.. and get rid of a lot of the loops.
#!/usr/bin/env python3
import json
output = "For entry {} this is the list {}"
data = '{"297050": [[12, 137], [193, 776]], "297056": [[12, 203]]}'
data = json.loads(data)
for k, v in data.items():
lists_with_commas = ", ".join([str(x) for x in v])
print(output.format(k, lists_with_commas), end=" ")
Output
For entry 297050 this is the list [12, 137], [193, 776] For entry 297056 this is the list [12, 203]
Explanation:
We use a template string.. it has {}
where we want to put stuff so we can run .format
on it later.
We only need the keys and the innermost lists. So we only need the one for
loop. We make sure we get the commas in the example by using .join
and inside there we do a list comprehension, which turns all the lists into strings inside v
.