{ }codelper
字典查找键是否存在P0063

电话簿查找

第一行给出电话簿中的人数 n。
接下来 n 行每行给出 "姓名 号码",用一个空格分隔。
再下一行给出查询数 q,接下来 q 行每行给出一个要查的姓名。
对每个查询输出该姓名的号码,占一行;如果电话簿中没有这个姓名,输出 "无"。

输入
1 ≤ n ≤ 1000,1 ≤ q ≤ 1000。
姓名为 1 到 12 个小写英文字母,在电话簿中互不相同。
号码为 1 到 20 个由数字和 '-' 组成的字符(无空格)。
查询的姓名也是 1 到 12 个小写英文字母
输出
q 行,每行一个号码或 "无"
样例 1 · stdin
3
kim 010-1234-5678
lee 02-555-0101
park 031-777-8888
3
lee
choi
kim
stdout
02-555-0101
无
010-1234-5678
main.py
输入(stdin)

运行时这些行会依次作为 input()/标准输入传入(运行中不会等待输入)。

$ 就绪

请在电脑上打开以编写和运行代码。在手机上可以查看题目和题解。

其他语言怎么写?查看各语言题解 · 8 种语言题解

陷阱在于查找不存在的姓名,各语言反应不同:Python book[name] 会因 KeyError 停止(用 book.get(name, "unknown")),C# book[name] 抛出 KeyNotFoundException(用 TryGetValue),Java get 悄悄返回 null,直接拼接会输出 "null"(用 getOrDefault)。
JS 用空对象 {} 查找会得到 undefined,更糟的是 "constructor" in book 为真,会拿到 Object.prototype 上的函数——请用 Map 和 has/get。
C++ book[name] 在键不存在时会插入一个空值,所以用 find 查询。
C 没有字典,先按姓名 qsort,再用 bsearch 查找。
Craykon 先用 book.包含(name) 询问 字典(),再读取(读取不存在的键会像 Python 一样停止)。

Pythonmain.py · 11 行
import sys lines = sys.stdin.read().split("\n")n = int(lines[0])book = {}for line in lines[1:n + 1]:    name, number = line.split()    book[name] = numberq = int(lines[n + 1])for name in lines[n + 2:n + 2 + q]:    print(book.get(name, "无"))
JavaScriptmain.js · 14 行
const lines = require("fs").readFileSync(0, "utf8").split("\n");const n = Number(lines[0]);const book = new Map();for (let i = 1; i <= n; i++) {  const [name, number] = lines[i].split(" ");  book.set(name, number);}const q = Number(lines[n + 1]);const out = [];for (let i = 0; i < q; i++) {  const name = lines[n + 2 + i].trim();  out.push(book.has(name) ? book.get(name) : "无");}console.log(out.join("\n"));
TypeScriptmain.ts · 15 行
import { readFileSync } from "node:fs";const lines: string[] = readFileSync(0, "utf8").split("\n");const n: number = Number(lines[0]);const book = new Map<string, string>();for (let i = 1; i <= n; i++) {  const [name, number] = lines[i].split(" ");  book.set(name, number);}const q: number = Number(lines[n + 1]);const out: string[] = [];for (let i = 0; i < q; i++) {  const name: string = lines[n + 2 + i].trim();  out.push(book.get(name) ?? "无");}console.log(out.join("\n"));
JavaMain.java · 24 行
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.HashMap;import java.util.Map; public class Main {    public static void main(String[] args) throws IOException {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        int n = Integer.parseInt(in.readLine().trim());        Map<String, String> book = new HashMap<>();        for (int i = 0; i < n; i++) {            String[] parts = in.readLine().trim().split(" ");            book.put(parts[0], parts[1]);        }        int q = Integer.parseInt(in.readLine().trim());        StringBuilder out = new StringBuilder();        for (int i = 0; i < q; i++) {            String name = in.readLine().trim();            out.append(book.getOrDefault(name, "无")).append('\n');        }        System.out.print(out);    }}
C#Main.cs · 22 行
using System;using System.Collections.Generic; class Program{    static void Main()    {        int n = int.Parse(Console.ReadLine());        var book = new Dictionary<string, string>();        for (int i = 0; i < n; i++)        {            string[] parts = Console.ReadLine().Split(' ');            book[parts[0]] = parts[1];        }        int q = int.Parse(Console.ReadLine());        for (int i = 0; i < q; i++)        {            string name = Console.ReadLine().Trim();            Console.WriteLine(book.TryGetValue(name, out string number) ? number : "无");        }    }}
C++main.cpp · 21 行
#include <iostream>#include <string>#include <unordered_map> int main() {    int n, q;    std::cin >> n;    std::unordered_map<std::string, std::string> book;    for (int i = 0; i < n; i++) {        std::string name, number;        std::cin >> name >> number;        book[name] = number;    }    std::cin >> q;    for (int i = 0; i < q; i++) {        std::string name;        std::cin >> name;        auto it = book.find(name);        std::cout << (it != book.end() ? it->second : "无") << '\n';    }}
Cmain.c · 31 行
#include <stdio.h>#include <stdlib.h>#include <string.h> struct Entry {    char name[13];    char number[32];}; static int by_name(const void *pa, const void *pb) {    const struct Entry *a = pa, *b = pb;    return strcmp(a->name, b->name);} int main(void) {    static struct Entry book[1000];    int n, q;    scanf("%d", &n);    for (int i = 0; i < n; i++) scanf("%12s %31s", book[i].name, book[i].number);    /* C에는 사전이 없다: 이름 순으로 정렬해 두고 bsearch로 찾는다 */    qsort(book, n, sizeof book[0], by_name);    scanf("%d", &q);    for (int i = 0; i < q; i++) {        struct Entry key;        scanf("%12s", key.name);        struct Entry *found = bsearch(&key, book, n, sizeof book[0], by_name);        if (found) puts(found->number);        else puts("无");    }    return 0;}
Craykonmain.cray · 20 行
n = 控制台.读行().转数字();book = 字典();循环 (i = 0; i < n; i++){    parts = 控制台.读行().分割();    book[parts[0]] = parts[1];}q = 控制台.读行().转数字();循环 (i = 0; i < q; i++){    name = 控制台.读行().去空白();    如果 (book.包含(name))    {        控制台.输出(book[name]);    }    否则    {        控制台.输出("无");    }}