python嵌套字典比较值与取值的实现示例
作者:北漂的雷子 时间:2023-12-25 01:28:35
前言
本文通过示例给大家介绍了python嵌套字典比较值,取值,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。
示例代码
#取值import types
allGuests = {'Alice': {'apples': 5, 'pretzels': {'12':{'beijing':456}}},
'Bob': {'ham sandwiches': 3, 'apple': 2},
'Carol': {'cups': 3, 'apple pies': 1}}
def dictget(dict1,obj,default=None):
for k,v in dict1.items():
if k == obj:
print(v)
else:
if type(v) is dict:
re=dictget(v,obj)
if re is not default:
print(re)
dictget(allGuests,'beijing')
结果:
比较大小
def bijiaodict(dict1,dict2):
for k,v in dict1.items():
for k2,v2 in dict2.items():
if k==k2 and v==v2:
print('dict1=dict2')
else:
print('dict1!=dict2')
dict1={'2':'6'}
dict2={2:{1:{1:8}}}
bijiaodict(dict1,dict2)
结果:
python字典嵌套字典的情况下获取某个key的value
正好最近在用python写接口的测试程序,期间用到解析字典获取某个key的value,由于多个接口返回的字典格式不是固定的并存在多层嵌套的情况。在字典的方法中也没有找到可直接达到目的的方法,于是自己写了个程序。分享给大家:
#coding: utf-8
import types
#获取字典中的objkey对应的值,适用于字典嵌套
#dict:字典
#objkey:目标key
#default:找不到时返回的默认值
def dict_get(dict, objkey, default):
tmp = dict
for k,v in tmp.items():
if k == objkey:
return v
else:
if type(v) is types.DictType:
ret = dict_get(v, objkey, default)
if ret is not default:
return ret
return default
#如
dicttest={"result":{"code":"110002","msg":"设备设备序列号或验证码错误"}}
ret=dict_get(dicttest, 'msg', None)
print(ret)
来源:http://www.cnblogs.com/leiziv5/p/7064070.html
标签:python,嵌套字典,取值
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
如何实现论坛的树状记录表展开技术?
2010-05-19 21:37:00
python实现数据结构中双向循环链表操作的示例
2023-09-05 00:36:47
Matplotlib中rcParams使用方法
2022-12-14 03:41:46
![](https://img.aspxhome.com/file/2023/1/90361_0s.png)
ASP常见错误详解及解决方案小结 推荐第1/2页
2011-02-24 11:19:00
pip安装python库的方法总结
2023-04-17 00:31:09
Python面向对象编程基础解析(一)
2021-08-10 15:05:12
Python的条件语句与运算符优先级详解
2023-06-21 07:43:49
![](https://img.aspxhome.com/file/2023/9/121709_0s.jpg)
Python生成随机数的方法详解(最全)
2023-05-04 12:36:08
![](https://img.aspxhome.com/file/2023/5/71355_0s.png)
解决python3捕获cx_oracle抛出的异常错误问题
2023-01-21 17:51:26
Python基础语法之变量与数据类型详解
2022-06-21 17:52:36
![](https://img.aspxhome.com/file/2023/3/65533_0s.png)
将Django项目迁移到linux系统的详细步骤
2021-02-11 02:13:09
![](https://img.aspxhome.com/file/2023/6/125146_0s.png)
NopCommerce架构分析(一)Autofac依赖注入类生成容器
2023-07-11 21:20:27
Python编程pytorch深度卷积神经网络AlexNet详解
2022-02-18 10:28:40
![](https://img.aspxhome.com/file/2023/5/105235_0s.png)
python实现文件助手中查看微信撤回消息
2023-09-03 07:23:50
SQL进行排序、分组、统计的10个新技巧分享
2024-01-17 22:44:12
Python实现根据日期获取当天凌晨时间戳的方法示例
2023-08-04 14:16:46
python二叉树常用算法总结
2023-01-15 01:35:18
NLTK的安装教程及安装错误解决方案
2022-09-24 04:59:33
![](https://img.aspxhome.com/file/2023/2/68282_0s.png)
ASP.NET程序中用Repeater实现分页
2024-05-09 09:02:48
![](https://img.aspxhome.com/file/2023/6/129816_0s.gif)
Vue利用mockjs编写假数据并应用的问题记录
2024-04-28 09:27:31