首页 > 解决方案 > 如果匹配,比较两个字典提取键

问题描述

保存在 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}我需要从TypeColortest.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'])

标签: pythondictionary

解决方案


请记住,您的 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}))


推荐阅读