Write me python code that matches 2 json files with categories and subcategories and then shows the percentage of match they have based on a newly made up legend
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here's a possible solution to match two JSON files containing categories and subcategories and calculate the percentage of match based on a newly made up legend:
First, let's define the legend that maps the categories and subcategories to their respective scores:
Next, let's read the two JSON files into Python dictionaries:
python
import json
with open('file1.json') as f1:
data1 = json.load(f1)
with open('file2.json') as f2:
data2 = json.load(f2)
Now, let's create two empty dictionaries to store the scores for each JSON file:
python
scores1 = {}
scores2 = {}
We'll iterate over the categories and subcategories in the first JSON file and add up the scores based on the legend:
python
for category, subcats in data1.items():
total = 0
for subcat, value in subcats.items():
if value:
total += legend[category][subcat]
scores1[category] = total
We'll do the same for the second JSON file:
python
for category, subcats in data2.items():
total = 0
for subcat, value in subcats.items():
if value:
total += legend[category][subcat]
scores2[category] = total
Now, let's calculate the percentage of match between the two JSON files for each category:
python
matches = {}
for category in set(scores1.keys()) | set(scores2.keys()):
match = 0
if category in scores1 and category in scores2:
match = max(scores1[category], scores2[category]) / sum(scores1[category], scores2[category])
matches[category] = match * 100
Finally, let's print out the results:
python
for category, match in matches.items():
print(f'{category}: {match:.2f}%')
Putting it all together, here's the complete code:
python
legend = {
'category1': {
'subcat1': 10,
'subcat2': 20,
'subcat3': 30
},
'category2': {
'subcat1': 15,
'subcat2': 25,
'subcat3': 35
}
}
import json
with open('file1.json') as f1:
data1 = json.load(f1)
with open('file2.json') as f2:
data2 = json.load(f2)
scores1 = {}
scores2 = {}
for category, subcats in data1.items():
total = 0
for subcat, value in subcats.items():
if value:
total += legend[category][subcat]
scores1[category] = total
for category, subcats in data2.items():
total = 0
for subcat, value in subcats.items():
if value:
total += legend[category][subcat]
scores2[category] = total
matches = {}
for category in set(scores1.keys()) | set(scores2.keys()):
match = 0
if category in scores1 and category in scores2:
match = max(scores1[category], scores2[category]) / sum(scores1[category], scores2[category])
matches[category] = match * 100
for category, match in matches.items():
print(f'{category}: {match:.2f}%')
Note that the above code assumes that the JSON files contain nested dictionaries where the keys at the top level correspond to category names and