2

Code:

import json

numbers = [2, 3, 5, 7, 11, 13]
letters = ["a", "b", "c", "d"]
filename = 'numbers.json'

with open(filename, 'w') as f_obj:
    json.dump(numbers, f_obj)
    json.dump(letters, f_obj)


with open(filename) as f_obj:
    numbers = json.load(f_obj)
    letters = json.load(f_obj)

print(numbers)
print(letters)

I would like to be able to read multiple lists which I have added to a json file and set them as separate lists which can be used later.

I don't mind having to adding a new line between each list in the json file and then reading it in line format.

1
  • what is your issue? Commented Oct 10, 2017 at 20:18

1 Answer 1

3

why not store them inside a global dictionary ?

import json

numbers = [2, 3, 5, 7, 11, 13]
letters = ["a", "b", "c", "d"]
filename = 'numbers.json'

val={'numbers': numbers, 'letters':letters}

with open(filename, 'w') as f_obj:
    json.dump(val, f_obj)


with open(filename) as f_obj:
    val = json.load(f_obj)
    numbers = val['numbers']
    letters = val['letters']

print(numbers)
print(letters)
Sign up to request clarification or add additional context in comments.

8 Comments

Thank you very much! I was usually scared of using dictionaries so I just used lists for everything but it seems that dictionaries may just be the way forward, thanks again.
you could also put all the lists inside one global list, but the dictionary makes it easier to retrieve elements by name ( instead of using indexes, and having to remember what index matches each list..)
PRMoureu, Could you do this with dictionaries containing dictionaries?
Sure, you just have to give a key and an object as value, and the value can be many kinds of objects in Python, string, integers, sets, classes, functions, dictionaries ... val={'numbers': numbers, 'letters':letters, 'new_dict':{'a':[1,2,3]}}. Next step : the keys don't need to be strings, you could use integers or other immutable types : val = {1:numbers, 2:letters}... dictionaries are your friends, don't fear them ;-)
Sorry but I don't understand the "val={'numbers': numbers, 'letters':letters, 'new_dict':{'a':[1,2,3]}}. " Specifically why's there's so many curly brackets.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.