#K34122. Group Records by City

    ID: 25240 Type: Default 1000ms 256MiB

Group Records by City

Group Records by City

You are given a list of records, each record containing four fields: id (an integer), age (an integer), name (a string) and city (a string). Your task is to group these records by their city field and then sort each group in ascending order by the id field.

The problem can be formally described as follows:

Given a list of records \( R = [r_1, r_2, \dots, r_n] \), where each record \( r_i \) is a dictionary with keys \( \{id, age, name, city\} \), produce a dictionary \( G \) such that for every city \( c \) that appears in \( R \), \( G[c] \) is a list of all records with city equal to \( c \), sorted in increasing order of id. That is, if \( r_a \) and \( r_b \) are two records in \( G[c] \) and \( r_a.id \gt r_b.id \), then their order should be reversed so that the smaller id comes first.

Note: The input and output for this problem will be handled via standard input (stdin) and standard output (stdout), respectively.

inputFormat

The input is read from standard input (stdin) and has the following format:

  1. The first line contains an integer n, which is the number of records.
  2. The following n lines each contain a record with four space-separated values in the following order: id (integer), age (integer), name (string), and city (string). Note that the city field will not contain spaces (for example, use underscores to separate words, e.g. New_York).

For example:

5
3 25 John New_York
1 22 Jane New_York
2 28 Doe Los_Angeles
4 20 Dana Los_Angeles
5 30 Mike Chicago

outputFormat

The output should be a JSON object printed to standard output (stdout). The keys are the city names, and the values are lists of JSON objects representing the records for that city. The records within each list must be sorted in ascending order by their id.

For example, the expected output for the sample input above is:

{"New_York": [{"id": 1, "age": 22, "name": "Jane", "city": "New_York"}, {"id": 3, "age": 25, "name": "John", "city": "New_York"}], "Los_Angeles": [{"id": 2, "age": 28, "name": "Doe", "city": "Los_Angeles"}, {"id": 4, "age": 20, "name": "Dana", "city": "Los_Angeles"}], "Chicago": [{"id": 5, "age": 30, "name": "Mike", "city": "Chicago"}]}
## sample
5
3 25 John New_York
1 22 Jane New_York
2 28 Doe Los_Angeles
4 20 Dana Los_Angeles
5 30 Mike Chicago
{"New_York": [{"id": 1, "age": 22, "name": "Jane", "city": "New_York"}, {"id": 3, "age": 25, "name": "John", "city": "New_York"}], "Los_Angeles": [{"id": 2, "age": 28, "name": "Doe", "city": "Los_Angeles"}, {"id": 4, "age": 20, "name": "Dana", "city": "Los_Angeles"}], "Chicago": [{"id": 5, "age": 30, "name": "Mike", "city": "Chicago"}]}