Model Series.map with a dictionary, including the NaN it gives for codes it does not know.
What to build
A program that maps country codes to names and reports the result.
Requirements
- Print each mapped value in input order, then
counts:followed byNAME: Clines for the mapped names, highest count first and equal counts in alphabetical order, thenunmapped: U.
Input
Line 1: m. Then m lines CODE NAME. Next line: the codes to map, separated by spaces.
Output
The mapped values, then the counts.
Constraints
1 ≤ m ≤ 50; 1 to 200 codes; names are single words.
Example
Input:
3
BD Bangladesh
FR France
JP Japan
BD JP XX BD FR
Output:
Bangladesh
Japan
NaN
Bangladesh
France
counts:
Bangladesh: 2
France: 1
Japan: 1
unmapped: 1
Why it works
map looks every value up in the dictionary, and pandas has no name for a code that is missing, so it marks it NaN; counting those NaNs is how you catch a mapping that is incomplete.
Examples
3 BD Bangladesh FR France JP Japan BD JP XX BD FR
Bangladesh Japan NaN Bangladesh France counts: Bangladesh: 2 France: 1 Japan: 1 unmapped: 1
1 A Alpha A
Alpha counts: Alpha: 1 unmapped: 0
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Read the mapping into a dictionary; a code not in it maps to NaN.
Hint 2
Count the mapped values, then list them by count (highest first, then by name).
Solution
Show one correct solution (try it yourself first)
m = int(input())
names = dict(input().split() for _ in range(m))
codes = input().split()
mapped = [names.get(c, "NaN") for c in codes]
for v in mapped:
print(v)
counts = {}
for v in mapped:
if v != "NaN":
counts[v] = counts.get(v, 0) + 1
print("counts:")
for name, c in sorted(counts.items(), key=lambda kv: (-kv[1], kv[0])):
print(f"{name}: {c}")
print(f"unmapped: {mapped.count('NaN')}")