With a list of dictionaries, in a json dataset (mydata.json) looking like this:
[
{"A": "123", "B": "456", "C": "789", "D": "1011"},
{"A": "1213", "B": "1415", "C": "1617", "D": "1819"},
...
]
I am attempting to loop through each dictionary, and extract each key-value pair in the order in which it is stored.
I wish to retain the A, B, C, D sequence in that specific order per dictionary to be able to pass them into another piece of code that will process it further.
For simplicity, I'm testing it with printing each step through each iteration of the below nested for-loop.
Unfortunately it doesn't process the dictionaries in the way that I would need.
I need access to each key-value pair, per each loop, in that order, e.g. the first dictionary containing the key A, should be succeeded by the first B-C-D of that same dict.
Then the second dictionary should be processed, starting with A, then B-C-D, etc.
What I tried:
with open("mydata.json", "r") as read_file:
md = json.load(read_file)
for d in md:
for k,v in d.items():
if (k == "A"):
print(k + ": " + v)
continue
if (k == "B"):
print(k + ": " + v)
continue
if (k == "C"):
print(k + ": " + v)
continue
if (k == "D"):
print(k + ": " + v)
continue
else:
continue
Desired output (strict sequential order):
A: 123
B: 456
C: 789
D: 1011
A: 1213
B: 1415
C: 1617
D: 1819
Actual output (scrambled order):
B: 456
D: 1011
A: 123
C: 789
A: 1213
C: 1617
... etc.
Any advice is greatly appreciated.
EDIT:
I have indeed marked my question as a duplicate, apologies for this! If I need to delete it altogether, to reduce clutter in SO, please leave a comment suggesting this. Thanks for the help!