博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
万能函数:读取字典dict以及json里面,任意key对应的value
阅读量:2392 次
发布时间:2019-05-10

本文共 5129 字,大约阅读时间需要 17 分钟。

1.背景知识:

(1)items()遍历字典

my_dict = {    "name":"alien",    "country":"china",    "other":{        "age":"18",        "gender":"man",    },    "school":"HLW"}(1)获取字典里面的key,vaule,遍历每个元祖def read_dict_all(dict_str):    for i in dict_str.items():         # items()函数可以获取对象的key,value        print(i)read_dict_all(my_dict)(2)获取字典里面的key,vaule,都是单独的字符串def read_dict_only(dict_str):    for k,v in dict_str.items():        print(k,v)read_dict_only(my_dict)(3)获取字典里面的key或value,获取的是单独字符串def read_dict_only_k(dict_str):    for k,v in dict_str.items():        print(k)read_dict_only_k(my_dict)

最终结果:

('name', 'alien')('country', 'china')('other', {
'age': '18', 'gender': 'man'})('school', 'HLW')name aliencountry chinaother {
'age': '18', 'gender': 'man'}school HLWnamecountryotherschool

(2)values() & keys()遍历字典

my_dict = {    "name":"alien",    "country":"china",    "other":{        "age":"18",        "gender":"man",        "family":{            "wife":"lily",            "pet":"nuomi"        }    },    "school":"HLW"}for i in my_dict.keys():    print(i)print('+'*30)for i in my_dict.values():    print(i)

最终结果:

namecountryotherschool++++++++++++++++++++++++++++++alienchina{
'age': '18', 'gender': 'man', 'family': {
'wife': 'lily', 'pet': 'nuomi'}}HLW

(3)return在for循环里面使用注意的要点

def dict_get(dict_str):    for key in dict_str.keys():        return key       ##for循环的时候,如果return之前可能有多个结果,那只返回第一个结果def dict_read(dict_str, key_t):    for key in dict_str.keys():        if key==key_t:   ## return之前,需要确定唯一的结果时候,再return结果            return dict_str.get(key_t)my_dict = {    "name":"alien",    "country":"china",    "school":"HLW"}r = dict_get(my_dict)print(r)r =dict_read(my_dict,"school")print(r)

最终结果:

nameHLW

2.读取字典里任意深度的key对应的value

(1)方式一

my_dict = {    "name":"alien",    "country":"china",    "other":{        "age":"18",        "gender":"man",        "family":{            "wife":"lily",            "pet":"nuomi"        }    },    "school":"HLW"}def read_dict(dict_str,key):    for k, v in dict_str.items():        if k == key:            return v        if type(v) is dict:                  return read_dict(v,key)    return "在dic()里面未发现目标key"r_pet = read_dict(my_dict, "pet")           # 读取第三级字典的keyprint(r_pet)r_gender = read_dict(my_dict,'gender')      # 读取第二季字典的keyprint(r_gender)r_alien = read_dict(my_dict,'alien')        # 非dict里面的keyprint(r_alien)

最终结果:

nuomiman在dic()里面未发现目标key

(2)方式二

def dict_get(dict_str, key_t):    if isinstance(dict_str, dict):        for v in dict_str.values():            if key_t in dict_str.keys():                return dict_str.get(key_t)            else:                if type(v) is dict:                            return dict_get(v,key_t)    return '传入的字符串不是字典或未查到目标key_t'

错误解读:

def dict_get(dict_str, key_t):    if isinstance(dict_str, dict):        for v in dict_str.values():            if key_t in dict_str.keys():                return dict_str.get(key_t)            else:                    return dict_get(v,key_t)         return '传入的字符串不是字典或未查到目标key_t'
  • 如果要找的是key是“pet”,那么在在第一个for循环的时候,从for直接跳到else,而此时的v是alien,alien不是字典
  • 所以alien带入函数dict_get()的时候,会直接被return无法进入if isinstance()函数

(3)方式三

def dict_get(dict_str, key_t):    if isinstance(dict_str,dict):        if key_t in dict_str.keys():            return dict_str.get(key_t)        else:            for v in dict_str.values():                if type(v) is dict:                    return dict_get(v,key_t)    return '传入的字符串不是字典或未查到目标key_t'

错误解读:

def dict_get(dict_str, key_t):    if isinstance(dict_str,dict):        if key_t in dict_str.keys():            return dict_str.get(key_t)        else:            for v in dict_str.values():                return dict_get(v,key_t)
  • 错误的地方与方式二一样

错误解读三:

def dict_get(dict_str, key_t):    if isinstance(dict_str,dict):        for key in dict_str.keys():            if key_t in dict_str.keys():                return dict_str.get(key_t)            else:                return dict_get(dict_str.get(key), key_t)
  • return里面 dict_str.get(key)这个也不一定是字典,如果目标key是pet,那么第一个for循环的时候,alien带入return的dict_get()函数,最终肯定也会返回none,

3.读取json里面任意深度的key对应的value

json_str = [    {        "name": "alien",        "country": "china",        "other": {            "age": "18",            "gender": "man",            "family": {                "wife": "lily",                "pet": "nuomi"            }        },        "school": "清华"    },    {        "name": "lily",        "country": "china",        "other": {            "age": "20",            "gender": "woman",        },        "school": "北大"    }]def print_keyvalue_by_key(input_json, key):    key_value = ''    if isinstance(input_json, dict):        for json_result in input_json.values():            if key in input_json.keys():                key_value = input_json.get(key)            else:                print_keyvalue_by_key(json_result, key)    elif isinstance(input_json, list):        for json_array in input_json:            print_keyvalue_by_key(json_array, key)    if key_value != '':        print(str(key) + " = " + str(key_value))print_keyvalue_by_key(json_str,'name')print_keyvalue_by_key(json_str,"pet")

最终结果:

name = alienname = lilypet = nuomi

转载地址:http://boeab.baihongyu.com/

你可能感兴趣的文章
利用-TensorFlow-构建卷积神经网络
查看>>
利用-TensorFlow-实现排序和搜索算法
查看>>
利用TensorFlow实现卷积神经网络做文本分类
查看>>
如何构建高可读性和高可重用的-TensorFlow-模型
查看>>
使用TensorFlow识别交通标志
查看>>
122. Best Time to Buy and Sell Stock II [medium] (Python)
查看>>
推荐-线下AUC提升,线上CTR无提升
查看>>
Ubuntu 安装 pylucene 踩坑还原记,并安装 SmartChineseAnalyzer
查看>>
Java编程思想学习笔记(10)
查看>>
Java编程思想学习笔记(11)
查看>>
机器学习实战:基于Scikit-Learn和TensorFlow—第五章笔记
查看>>
Java编程思想学习笔记(12)
查看>>
Java编程思想学习笔记(13)
查看>>
Java编程思想学习笔记(14)
查看>>
Java-8-UnaryOperator
查看>>
Java-8-Function
查看>>
Java-8-Stream接口
查看>>
Junit4入门
查看>>
Java与算法(11)
查看>>
Java与算法(12)
查看>>