Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is recommended way to store dictionaries and json file type in python

I'm pulling json data from an API. My script will store this data and add information about this data to a dictionary.

To store the json data, i'm planning on using:

with open('data.json', 'w') as f:
     json.dump(data, f)

What would be an appropriate way to store the dictionary ? Would it be appropriate to convert the dict to json format with

json_str = json.dumps(dict1)

and save it in the same way as above ?

like image 435
David Hancock Avatar asked Dec 05 '25 10:12

David Hancock


1 Answers

You should save JSON data in a Python list or a dict, depending on the structure of your JSON data.

From http://www.json.org/:

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

The json library is what's commonly used to load JSON data and store it in a Python object. Note however that the load method will return (recursively) a Python list if the JSON data is like [...] and a Python dict if the JSON data is like {...}.

To read a JSON file containing a {...} and save its content to a dictionary data structure use:

>>> with open('data.json', 'r') as f:
...   data = json.load(f)
...
>>> type(data)
<type 'dict'>

If the file contains a JSON list [...] then:

>>> type(data)
<type 'list'>

Similarly when reading JSON data from a URL:

>>> response = urllib2.urlopen(URL)
>>> data = json.load(response)

You can always convert a list to a dictionary for example like this:

>>> dataD = dict([i,data[i]] for i in xrange(len(data)))

By doing so however you lose the order information provided by the JSON array structure.

like image 198
user2314737 Avatar answered Dec 08 '25 00:12

user2314737



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!