首页 > 编程知识 正文

python字符串与列表区别,python2 python3 初学

时间:2023-05-06 20:59:50 阅读:213070 作者:1481

I'm working with the json module creating a json file containing entries of the like

json.dumps({"fields": { "name": "%s", "city": "%s", "status": "%s", "country": "%s" }})

However, in the json-file created the fields are in the wrong order

{"fields": {"status": "%s", "city": "%s", "name": "%s", "country": "%s"}}

which is a problem because the substitions for the %s-strings are now incorrect.

How can I force the dumps function to keep the given order?

Like the other answers correctly state, before Python 3.6, dictionaries are unordered.

That said, JSON is also supposed to have unordered mappings, so in principle it does not make much sense to store ordered dictionaries in JSON. Concretely, this means that upon reading a JSON object, the order of the returned keys can be arbitrary.

A good way of preserving the order of a mapping (like a Python OrderedDict) in JSON is therefore to output an array of (key, value) pairs that you convert back to an ordered mapping upon reading:

>>> from collections import 和谐的绿草/p>

>>> import json

>>> d = OrderedDict([(1, 10), (2, 20)])

>>> print d[2]

20

>>> json_format = json.dumps(d.items())

>>> print json_format # Order maintained

[[1, 10], [2, 20]]

>>> OrderedDict(json.loads(json_format)) # Reading from JSON: works!

>>> _[2] # This works!

20

(Note the way the ordered dictionary is constructed from a list of (key, value) pairs: OrderedDict({1: 10, 2: 20}) would not work: its keys are not necessarily ordered as in the dictionary literal, since the literal creates a Python dictionary whose keys are unordered.)

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。