#C3636. Sort List of Dictionaries by Attribute
Sort List of Dictionaries by Attribute
Sort List of Dictionaries by Attribute
You are given an attribute (as a string) and a JSON array representing a list of dictionaries. Your task is to sort the list in ascending order based on the value corresponding to the given attribute. Each dictionary in the list is expected to contain the specified attribute. If the input does not meet the requirements (for example, if the attribute is missing in any dictionary or if the input format is invalid), output None
.
The solution should read from standard input (stdin) and produce the result on standard output (stdout). The input consists of two lines:
- The first line is a string representing the attribute by which to sort.
- The second line is a JSON array of dictionaries.
If the input is valid, output the JSON representation of the sorted list. Otherwise, output None
.
Note: When using mathematical notations, use the LaTeX format. For example, the sorting order can be described as: \(a[attribute] < b[attribute]\) for two dictionaries a and b.
inputFormat
The input is provided via standard input and consists of two lines:
- Line 1: A string that specifies the attribute to sort by.
- Line 2: A JSON array of dictionaries. Each dictionary must include the attribute provided in Line 1.
For example:
price [{"name": "apple", "price": 5}, {"name": "banana", "price": 2}, {"name": "cherry", "price": 7}]
outputFormat
The output should be printed to standard output. If the input is valid, print the JSON array of dictionaries sorted in ascending order according to the given attribute. If the input is invalid (e.g., the attribute is missing in one or more dictionaries, or the JSON is not in the expected format), print None
.
For example, for the sample input above, the output would be:
[{"name": "banana", "price": 2}, {"name": "apple", "price": 5}, {"name": "cherry", "price": 7}]## sample
price
[{"name": "apple", "price": 5}, {"name": "banana", "price": 2}, {"name": "cherry", "price": 7}]
[{"name": "banana", "price": 2}, {"name": "apple", "price": 5}, {"name": "cherry", "price": 7}]