#C14074. Count Key Occurrences in JSON Dictionaries
Count Key Occurrences in JSON Dictionaries
Count Key Occurrences in JSON Dictionaries
You are given a JSON array of dictionaries and a key (a string). Your task is to count how many times each value appears for the specified key across all dictionaries. If a dictionary does not contain the given key, it should be skipped. Output the resulting counts as a JSON object.
Note: The input is provided in two lines; the first line is a JSON array of dictionaries, and the second line is the key to search for.
In mathematical terms, if we denote the input array as \(A\) and the given key as \(k\), then your program should compute a function \(f:V \to \mathbb{N}\) such that:
[ f(v)=\left|{d\in A:, d[k]=v}\right| ]
where \(V\) is the set of all values corresponding to key \(k\) in array \(A\). If no dictionary contains \(k\), return an empty JSON object.
inputFormat
The input consists of two lines:
- The first line contains a JSON array of dictionaries. Each dictionary may or may not contain the key of interest.
- The second line contains a string representing the key whose values need to be counted.
For example:
[{"color": "red"}, {"color": "blue"}, {"color": "red"}, {"color": "green"}, {"color": "blue"}, {"color": "blue"}] color
outputFormat
Output a JSON object representing the counts of each value corresponding to the input key. If no dictionary contains the key, output an empty JSON object {}.
For example, for the above input, the output should be:
{"red": 2, "blue": 3, "green": 1}## sample
[{"color": "red"}, {"color": "blue"}, {"color": "red"}, {"color": "green"}, {"color": "blue"}, {"color": "blue"}]
color
{"red": 2, "blue": 3, "green": 1}