#!/usr/bin/env python3
import json
# instantiate an empty dict
team = {}
# add a team member
team['tux'] = {'health': 23, 'level': 4}
team['beastie'] = {'health': 13, 'level': 6}
team['konqi'] = {'health': 18, 'level': 7}
Cheat sheet: Python 3.7 for beginners
Top Python GUI frameworks
Download: 7 essential PyPI libraries
Red Hat Developers
Latest Python content
This code creates a Python dictionary called team. It’s empty initially (you can create one that's already populated, but that’s impossible if you don’t have the data to put into the dictionary yet).
To add to the dict object, you create a key, such as tux, beastie, or konqi in the example code, and then provide a value. In this case, the value is another dictionary full of player statistics.
Dictionaries are mutable. You can add, remove, and update the data they contain as often as you please. This format is ideal storage for data that your application frequently uses.
Saving data in JSON format
If the data you’re storing in your dictionary is user data that needs to persist after the application quits, then you must write the data to a file on disk. This is where the JSON Python module comes in:
with open('mydata.json', 'w') as f:
json.dump(team, f)
This code block creates a file called mydata.json and opens it in write mode. The file is represented with the variable f (a completely arbitrary designation; you can use whatever variable name you like, such as file, FILE, output, or practically anything). Meanwhile, the JSON module’s dump function is used to dump the data from the dict into the data file.
Saving data from your application is as simple as that, and the best part about this is that the data is structured and predictable. To see, take a look at the resulting file:
$ cat mydata.json
{"tux": {"health": 23, "level": 4}, "beastie": {"health": 13, "level": 6}, "konqi": {"health": 18, "level": 7}}
Reading data from a JSON file
If you are saving data to JSON format, you probably want to read the data back into Python eventually. To do this, use the Python JSON module’s json.load function:
#!/usr/bin/env python3
import json
f = open('mydata.json')
team = json.load(f)
print(team['tux'])
print(team['tux']['health'])
print(team['tux']['level'])
print(team['beastie'])
print(team['beastie']['health'])
print(team['beastie']['level'])
# when finished, close the file
f.close()
This function implements the inverse, more or less, of saving the file: an arbitrary variable (f) represents the data file, and then the JSON module’s load function dumps the data from the file into the arbitrary team variable.
The print statements in the code sample demonstrate how to use the data. It can be confusing to compound dict key upon dict key, but as long as you are familiar with your own dataset, or else can read the JSON source to get a mental map of it, the logic makes sense.
Of course, the print statements don’t have to be hard-coded. You could rewrite the sample application using a for loop:
for i in team.values():
print(i)
Using JSON
As you can see, JSON integrates surprisingly well with Python, so it’s a great format when your data fits in with its model. JSON is flexible and simple to use, and learning one basically means you’re learning the other, so consider it for data storage the next time you’re working on a Python application.
You might want to also check the module 'simplejson'. They used to be identical, but json is built into the standard library whereas simplejson is maintained outside it, so they now differ. If you search the net about them, you happen to find many comparisons that address speed (some versions of one are faster/slower than some versions of the other in some operations, etc.). A particular consideration for me was that simplejson supported more types, for me these were Decimal [1] and datetime [2]. Since I didn't want to rely on an external library, which (also) was not built into EL7, I decided to use json, and had to patch my code [1][2] to handle them manually. No idea what's the current status in both' latest versions (latest json in python3 vs latest simplejson), but I guess they still differ in that respect. So if you intend to use them with non-trivial data (e.g. that you get from a complex db schema), do check and compare both, and then decide which one to use. Hope this helps,
[1] https://gerrit.ovirt.org/67352
[2] https://gerrit.ovirt.org/71130
The opinions expressed on this website are those of each author, not of the author's employer or of Red Hat.
Opensource.com aspires to publish all content under a Creative Commons license but may not be able to do so in all cases. You are responsible for ensuring that you have the necessary permission to reuse any work on this site. Red Hat and the Red Hat logo are trademarks of Red Hat, Inc., registered in the United States and other countries.
A note on advertising: Opensource.com does not sell advertising on the site or in any of its newsletters.
You might want to also check the module 'simplejson'. They used to be identical, but json is built into the standard library whereas simplejson is maintained outside it, so they now differ. If you search the net about them, you happen to find many comparisons that address speed (some versions of one are faster/slower than some versions of the other in some operations, etc.). A particular consideration for me was that simplejson supported more types, for me these were Decimal [1] and datetime [2]. Since I didn't want to rely on an external library, which (also) was not built into EL7, I decided to use json, and had to patch my code [1][2] to handle them manually. No idea what's the current status in both' latest versions (latest json in python3 vs latest simplejson), but I guess they still differ in that respect. So if you intend to use them with non-trivial data (e.g. that you get from a complex db schema), do check and compare both, and then decide which one to use. Hope this helps,
[1] https://gerrit.ovirt.org/67352
[2] https://gerrit.ovirt.org/71130
The opinions expressed on this website are those of each author, not of the author's employer or of Red Hat.
Opensource.com aspires to publish all content under a Creative Commons license but may not be able to do so in all cases. You are responsible for ensuring that you have the necessary permission to reuse any work on this site. Red Hat and the Red Hat logo are trademarks of Red Hat, Inc., registered in the United States and other countries.
A note on advertising: Opensource.com does not sell advertising on the site or in any of its newsletters.