簡體   English   中英

如果匹配,比較兩個字典提取鍵

[英]compare two dictionary extract key if matches

保存在測試中的字典。保存為文件的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}那么我需要從test.json中提取TypeColor

代碼如下

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}))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM