综合技术

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

微信扫一扫,分享到朋友圈

What is the recommended way to store dictionaries and the json file type in Python
0

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 ?

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.

阅读原文...


微信扫一扫,分享到朋友圈

What is the recommended way to store dictionaries and the json file type in Python
0

Hello, buddy!

继比特币后的又一金矿——IPFS存储挖矿

上一篇

Visual Studio 2012 PowerShell project

下一篇

评论已经被关闭。

插入图片

热门分类

往期推荐

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

长按储存图像,分享给朋友