python - 如果匹配,比较两个字典提取键
问题描述
保存在 test.json 中并保存为文件的字典如下
[
{
"applicationName": "Benz",
"Code": 101,
"Type": "Petrol",
"Color": "White"
},
{
"applicationName": "Tesla",
"Code": 102,
"Type": "Electric" ,
"Color":"Blue" },
{ "applicationName": "BMW",
"notificationCode": 103,
"Type": "Petrol" , "Color":"Black" } ]
如果我的输入是,那么d = {'Code': 102}
我需要从Type
Color
test.json
代码如下
import json
conf = json.loads(r'C:\users\Desktop\test.json')
sample = {}
if d['Code'] == conf['Code']:
sample.update(conf['Type'])
sample.update(conf['Color'])
解决方案
请记住,您的 json 是一个列表
import json
import json
def locate(code: str):
with open(r"C:\users\Desktop\test.json") as f:
cars = json.load(f)
for car in cars:
if car["Code"] == code:
return {"Type": car["Type"], "Color": car["Color"]}
return None
print(locate(101))
for 循环
import json
def locate(d):
with open(r"C:\users\Desktop\test.json") as f:
cars = json.load(f)
for i in range(0, len(cars)):
car = cars[i];
if car["Code"] == d["Code"]:
return {"Type": car["Type"], "Color": car["Color"]}
return None
print(locate({"Code": 102}))
你也可以使用next
import json
def locate(d):
with open(r"C:\users\Desktop\test.json") as f:
cars = json.load(f)
match = next((car for car in cars if car["Code"] == d["Code"]), None)
return {"Type": match["Type"], "Color": match["Color"]} if match else None
print(locate({"Code": 102}))
推荐阅读
- javascript - 重定向到维护页面
- php - 三向枢轴表 Laravel
- python - 如何提高python exe文件的速度?
- node.js - 节点使用变量内容执行shell命令
- swift - 长 RTL 文本在 SwiftUI 中被截断/溢出
- oauth - 使用给定令牌向 Twitch API 进行身份验证
- sql - 如何在'where'子句中使用laravel查询构建器中的括号?
- c# - 运行时错误是什么意思-内部CLR错误0x80131506
- r - 估算数值和分类的缺失值,并在 R 中对分类值进行居中和缩放,但有例外
- docker - 通过 OpenCL 在 Docker 中连接显卡