python-3.x - 如何检查嵌套(全部)字典中是否存在多个键?
问题描述
检查是否'b' & 'c'
存在于'a' & 'b'
.
test = {
'a': {
'b': [1234],
'c': 'some_value'
},
'd': {
'b': [5678],
'c': ''
}
}
方法 1:如果嵌套字典数量庞大,则按以下方式工作,但实现不是很好。而且,您不能准确地通知哪个元素不存在。比方说,'c' not in 'a' , 'b' not in 'd' & 'c' not in 'd'
。在这种情况下,它在第二条语句处失败(但它没有通知第三和第四条语句也失败)。我需要得到,这一切都不存在。
try:
v1 = test['a']['b']
v2 = test['a']['c']
v3 = test['d']['b']
v4 = test['d']['c']
except Exception as err:
print(err)
方法2:
for k,v in test.items():
if 'b' not in v:
print("'b' doesn't exist in {}".format(test[k][v]))
if 'c' not in v:
print("'c' doesn't exist in {}".format(test[k][v]))
Approach1
而且Approach2
似乎不是很好。还有其他更好的处理方法吗?
解决方案
如果只有两级嵌套,您能否尝试计算低级字典中键的出现次数?例如:
counter = {}
for el in test.keys():
for subkey in test.get(el).keys():
if subkey not in counter.keys():
counter[subkey] = 1.0
else:
counter[subkey] += 1.0
它会回来的
{'b': 2.0, 'c': 2.0}
基于此,您可以识别嵌套键中的重复值。
然后,您可以使用set
查看哪些键存在重复项:
复制密钥
counter = {k : v for k, v in counter.items() if v > 1}
#get only values with dupe records
{k:v for k, v in test.items() if len(set(counter.keys()).intersection(v)) > 0}
> {'a': {'b': [1234], 'c': 'some_value'}, 'd': {'b': [5678], 'c': ''}}
推荐阅读
- python - 在 Python 中更改堆积条形图图例
- java - 如何在android studio中解决“清单合并失败:”
- docker - 如何使用 docker 镜像运行 docker-compose?
- javascript - 带有 CKeditor 4.x 验证的 jQuery 表单验证器不起作用
- reactjs - 部署到 GitHub Pages 的 React 应用程序给出“未找到站点”
- javascript - 如何确保回调下面的代码始终在回调完成后运行
- arrays - 在给定范围内具有频率 k 的总数
- java - 当我运行以下命令时出现问题“Oracle Java (JDK) 8 Installer PPA (DISCONTINUED)” - $sudo add-apt-repository ppa:webupd8team/java
- graphql - Apollo graphQL - 您可以使用变量查询本地状态而无需使用解析器吗?
- c - 如果可以将此添加到此 switch 语句中吗?