使用各种编程语言遍历字典的方法

qrkoydzdhlje1年前 ⋅ 674 阅读
Python:

使用for循环遍历键和值

```
dict = {'name': 'Alice', 'age': 20, 'city': 'New York'}
for key, value in dict.items():
    print(key, value)
```

使用for循环遍历键

```
dict = {'name': 'Alice', 'age': 20, 'city': 'New York'}
for key in dict:
    print(key, dict[key])
```

使用while循环遍历键

```
dict = {'name': 'Alice', 'age': 20, 'city': 'New York'}
keys = list(dict.keys())
cnt = 0
while cnt < len(keys):
    print(keys[cnt], dict[keys[cnt]])
    cnt += 1
```

Java:

使用for-each循环遍历键和值

```
Map map = new HashMap<>();
map.put("name", "Alice");
map.put("age", "20");
map.put("city", "New York");
for (Map.Entry entry : map.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}
```

使用for-each循环遍历键

```
Map map = new HashMap<>();
map.put("name", "Alice");
map.put("age", "20");
map.put("city", "New York");
for (String key : map.keySet()) {
    System.out.println(key + ": " + map.get(key));
}
```

使用Iterator遍历键

```
Map map = new HashMap<>();
map.put("name", "Alice");
map.put("age", "20");
map.put("city", "New York");
Iterator iterator = map.keySet().iterator();
while (iterator.hasNext()) {
    String key = iterator.next();
    System.out.println(key + ": " + map.get(key));
}
```

C++:

使用for循环遍历键和值

```
map dict;
dict["name"] = "Alice";
dict["age"] = "20";
dict["city"] = "New York";
for (auto iter = dict.begin(); iter != dict.end(); iter++) {
    cout << iter->first << ": " << iter->second << endl;
}
```

使用for循环遍历键

```
map dict;
dict["name"] = "Alice";
dict["age"] = "20";
dict["city"] = "New York";
for (auto iter = dict.begin(); iter != dict.end(); iter++) {
    cout << iter->first << ": " << dict[iter->first] << endl;
}
```

使用while循环遍历键

```
map dict;
dict["name"] = "Alice";
dict["age"] = "20";
dict["city"] = "New York";
auto iter = dict.begin();
while (iter != dict.end()) {
    cout << iter->first << ": " << iter->second << endl;
    iter++;
}
```

以上是Python,Java和C++在遍历字典时的常用方法,其他编程语言也有类似的方法,只需要稍微调整一下语法即可。

全部评论: 0

    相关推荐