Dean219 Dean219 - 1 month ago 9
JSON Question

Getting key and value from a list containing JSON

I'm having issues getting a key and a value from a list in Python. The list itself contains a number of JSON lines structured as follows:

[{"values":"test","cost":"1234"},{"values":"test2","cost":"12345"}]


The issue is I would ideally not want to convert it to a dictionary as it would mean either populating one during the reading of the original JSON file and appending each JSON piece to a list and then the list to the dictionary.

I found I can print the keys simply by doing this:

for line in file:
mylist.append(json.loads(line))
for line in mylist:
for key in line.keys():
print(key)


This is again is all fine and it prints all the keys such as the example, "values","test" etc. But I cannot access the values of each by doing this as I would with a dictionary:

for line in file:
mylist.append(json.loads(line))
for line in mylist:
for key,value in line.keys():
print(value)


As this throws an error saying "too many values to unpack", is there a simpler solution which I have no considered? I have looked at many many other solutions but all seem to result in updating a dictionary and accessing key values through a dictionary but I would rather not have to append to a list then update a dictionary with each list.

Answer

To access both keys and values use the .items() method of the dictionary.

for key, value in line.items()

Also note that the .keys() in the first case is not necessary as iterating through a dictionary will normally return its keys.

for key in line: