python 字典fromskey
时间: 2024-01-19 18:17:28 浏览: 64
字典的fromkeys()方法用于创建一个新的字典,其中包含指定的键和相同的值。该方法的语法如下:
```python
new_dict = {}.fromkeys(keys, value)
```
其中,keys是一个列表或可迭代对象,表示要作为字典的键的值;value是可选参数,表示要为所有键设置的值,默认为None。
以下是两种使用字典的fromkeys()方法的例子:
1. 使用列表作为键创建字典
```python
name_list = ["fly1","fly2","fly3","fly1","fly2","fly3","fly1","fly2","fly3"]
new_name_dict = {}.fromkeys(name_list)
print(new_name_dict)
```
输出:
```
{'fly1': None, 'fly2': None, 'fly3': None}
```
2. 使用字符串作为键创建字典,并设置默认值
```python
name_list = ["fly1","fly2","fly3","fly1","fly2","fly3","fly1","fly2","fly3"]
new_name_dict = {}.fromkeys(name_list, 0)
print(new_name_dict)
```
输出:
```
{'fly1': 0, 'fly2': 0, 'fly3': 0}
```
阅读全文