• python-字典和json


    Python的字典和JSON在表现形式上非常相似

    #这是Python中的一个字典

    dic = { 'str': 'this is a string', 'list': [1, 2, 'a', 'b'], 'sub_dic': { 'sub_str': 'this is sub str', 'sub_list': [1, 2, 3] }, 'end': 'end' }

    这是javascript中的一个JSON对象

    json_obj = { 'str': 'this is a string', 'arr': [1, 2, 'a', 'b'], 'sub_obj': { 'sub_str': 'this is sub str', 'sub_list': [1, 2, 3] }, 'end': 'end' }

    实际上JSON就是Python字典的字符串表示,但是字典作为一个复杂对象是无法直接转换成定义它的代码的字符串(不能传递所以需要将其转换成字符串先),

    Python有一个叫simplejson的库可以方便的完成JSON的生成和解析,这个包已经包含在Python2.6中,

    就叫json 主要包含四个方法:

    dump和dumps(从Python生成JSON),

    load和loads(解析JSON成Python的数据类型)

    dump和dumps的唯一区别是dump会生成一个类文件对象,dumps会生成字符串,

    同理load和loads分别解析类文件对象和字符串格式的JSON

    json的用法可以是:就是字典的用法

    data = {"count": 20, "action_label": "click_search", "return_count": 19,
            "no_outsite_res": 0, "has_more": 1}

    print(data.keys())#获取键
    print(data.values())#获取值
    print(data.get('count'))#获取某个键的值

  • 相关阅读:
    补题列表
    task list
    UVa 11809
    UVA 272 TEX Quotes 题解
    莱州一中2016高考加油视频
    POJ2367-Genealogical tree-拓扑排序
    POJ1094-Sorting It All Out-拓扑排序
    POJ3660-Permutations-传递闭包FLOYD
    POJ3687- Labeling Balls-优先队列拓扑排序
    POJ1201-Intervals- 差分约束
  • 原文地址:https://www.cnblogs.com/R-bear/p/7188572.html
Copyright © 2020-2023  润新知