如果匹配,则比较两个字典提取键

时间:2021-01-19 02:46:29

标签: python dictionary

保存在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 中提取 Colortest.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'])

1 个答案:

答案 0 :(得分:1)

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