如何输出哈希表的数值
时间: 2024-11-22 20:47:26 浏览: 9
输出哈希表(也叫散列表)的数值通常取决于具体的语言和数据结构实现。以下是几种常见编程语言中输出哈希表内容的方式:
1. **Python (dict)**:
```python
hash_table = {'key1': 10, 'key2': 20}
for key, value in hash_table.items():
print(f"{key}: {value}")
```
2. **JavaScript (Object)**:
```javascript
let hashTable = {key1: 10, key2: 20};
for (let key in hashTable) {
console.log(key + ": " + hashTable[key]);
}
```
3. **Java (HashMap)**:
```java
Map<String, Integer> hashTable = new HashMap<>();
hashTable.put("key1", 10);
hashTable.put("key2", 20);
for (Map.Entry<String, Integer> entry : hashTable.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
```
4. **C# (Dictionary)**:
```csharp
Dictionary<string, int> hashTable = new Dictionary<string, int>();
hashTable.Add("key1", 10);
hashTable.Add("key2", 20);
foreach (KeyValuePair<string, int> pair in hashTable)
Console.WriteLine(pair.Key + ": " + pair.Value);
```
5. **C++ (unordered_map)**:
```cpp
std::unordered_map<std::string, int> hashTable;
hashTable["key1"] = 10;
hashTable["key2"] = 20;
for (const auto &pair : hashTable)
std::cout << pair.first << ": " << pair.second << "\n";
```
请注意,每种语言的语法可能会有所不同,上述例子展示了基本的思想。
阅读全文