Getting key and value from a list containing JSON

10,952

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:
Share:
10,952
D3181
Author by

D3181

Updated on June 28, 2022

Comments

  • D3181
    D3181 almost 2 years

    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.